简体   繁体   中英

How i can make a selected drop down list using jQuery on ruby on rails 2.0 ?

Hello i'm trying to make 2 drop down lists. the first i want to show all the categories and when the user selects the category he wants then automatically show all the subcategories of the category he selected and save the subcategory id. how i can do it?

the relationship of the category with the subcategory is that i'm storing the category id in the subcategory in integer format.

here is my code and what i have done until now. im not so familiar with jquery

<script type="text/javascript">
$(document).ready(function() {
 // hides the slickbox as soon as the DOM is ready
  $('#subcategory_value_id').hide();
         $('div#category_value').change(function () {
                    var category_id = "";

          $("select option:selected").each(function () {
          category_id += $(this).text();
              });
         $("div#test").text(category_id);
         $('#subcategory_value_id').toggle();
        })
         });  
   </script>

<div id="category_value">Country:
 <%= f.collection_select :id, Category.find(:all), :id, :name, :prompt => "Select a Category" %></div>
 </p>
<p>
  <div id="subcategory_value_id">State or Province:
  <%= f.collection_select :id, Subcategory.find(:all), :id, :name, :prompt => "Select a Subcategory" %></div>
</p>
<div id="test"></div>

Thank you

I've done this with countries and states in this project .

Here's the simplified view:

<%= address.collection_select :country_id, Country.all, :id, :name, { :selected => address.object.country_id.to_s } %>
<%= address.collection_select :state_id, address.country.states, :id, :name, { :selected => address.object.state_id.to_s } %>

Here is the JavaScript that:

  • Makes an AJAX request to populate a JSON structure with countries and states.
  • Adds onchange events to the countries select, which updates the state select.

Note that in my code, there is logic applies to both billing and shipping addresses, so your code would be simplified there. Also in my code, text is allowed for the state field, which would not be needed in your case. You don't necessarily have to populate a JSON array in an AJAX call - that could be included in the initial page load. The guts of what you want to look at is the onchange event functionality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM