Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails jquery cascading dropdown reloading

I have a three tier cascading dropdown in rails page, when country changes, state or province changes, then city changes.

I have done the feature by adding change event to country, province dropdown respectively. However, I still have to issues:

first, when reload the second and third tier dropdown lists are gone, how to keep them.

second, when editing, how to load the stored value last time?

Thanks in advance.

like image 985
Bruce Li Avatar asked Mar 31 '26 17:03

Bruce Li


1 Answers

I know I'm a litte late, but I had the same problem and found a solution at Railscasts. If you used the Railscast by Ryan Bates for Dynamic Select Boxes, which can be found here:

http://railscasts.com/episodes/88-dynamic-select-menus-revised

One of the users in the comments posted an updated coffee script to get this to work with an edit form:

jQuery ->
  loaded_product = $('#product_category_id :selected').text()
  categorys = $('#product_category_id').html()
  $('#product_category_id').parent().hide()
  if loaded_product.length != 0
   brand = $('#product_brand_id :selected').text()
   escaped_brand = brand.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
   options = $(categorys).filter("optgroup[label=#{escaped_brand}]").html()
   $('#product_category_id').html(options)
   $('#product_category_id').parent().show()
  console.log(categorys)
  $('#product_brand_id').change ->
    brand = $('#product_brand_id :selected').text()
    escaped_brand = brand.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
    options = $(categorys).filter("optgroup[label=#{escaped_brand}]").html()
    console.log(options)
    if options
      $('#product_category_id').html(options)
      $('#product_category_id').parent().show()
    else
      $('#product_category_id').empty()
      $('#product_category_id').parent().hide()

Maybe you can still use it or someone else finds this helpful.

like image 51
Thomas Avatar answered Apr 03 '26 09:04

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!