select and onChange in a Ruby on Rails form

rh4games picture rh4games · Dec 31, 2011 · Viewed 23.9k times · Source

I browsed all SO questions and answers about this topic but I'm still unable to make my scenario work. I want to trigger a click button action when a dropdown menu option is selected ; seems simple and should be very common with AJAX.

Here are the relevant excerpts of my code:

<%= form_for(@test, :html => {:id => "form_id", :name => "MyForm", :remote => "true"}) do |form| %>
    <%= form.label "Menu1" %>
    <%= form.select (:Menu1, [["Option1","value1"],["Option2","value2"]], :html_options=>{:onChange=>"javascript: this.form.apply_button_name.click();"}) %>

    <!-- more select menus and text fields here -->

    <div class="actions">
        <%= form.submit "Apply", :name => "apply_button_name", :remote => "true" %>
    </div>
<% end %>

I used ":remote => "true" both for the form and the button because that's the only way to get AJAX working. I also tried with and without explicit "html_options" and "javascript:", after I browsed some SO answers that suggested that but that did not help. I also tried onSelect, and onClick instead of onChange, but still no luck.

The generated HTML is the following:

    Menu1
    <select id="test_Menu1" name="test[Menu1]"><option value="value1">Option1</option>
<option value="value2" selected="selected">Option2</option></select>

As you can see, there's no onChange event handler in the HTML code ; WHY? Anyone is seeing what am I doing wrong?

Thanks for any help.

Answer

rabusmar picture rabusmar · Dec 31, 2011

Modify your call to form.select, like this:

<%= form.select :Menu1, [["Option1","value1"],["Option2","value2"]], {}, 
                :onChange=>"javascript: this.form.apply_button_name.click();" %>