select and onChange in a Ruby on Rails form

2020-02-11 02:20发布

问题:

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.

回答1:

Modify your call to form.select, like this:

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


回答2:

If you examine the documentation for:

API Dock Ruby on Rails select

You will see that the select form helper takes the form:

select(object, method, choices, options = {}, html_options = {})

If you don't pass anything for the option hash (in your case this will be an empty hash), the form thinks that your html_options hash are your options hash, and gets confused.

A way to check this is to add something like {:onchange=> "alert('Hello');"} and either see if the event successfully triggers, or alternatively, in your actual web page, right click on the select element and inspect it. If no onchange option is present in the html, that means that your rails form helper is indeed confusing the html_options with the other options. So, what you should have:

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

MAKE SURE TO INCLUDE THE EMPTY HASH FOR THE OPTIONS BEFORE THE HTML OPTIONS AND YOU SHOULD BE FINE. I don't think you even need to have the html_options and javascript stuff you have.

Lastly, if onChange doesn't work, try to use onchange with no capital C.