简体   繁体   中英

Populate select list options from ruby hash using jQuery

I have a ruby hash that contains car makes and models followed by the year. It looks like:

makes_a={"saturn"=>{"sky"=>["2007", "2009", "2008"], "l-series"=>["2004", "2000", "2005", "2003", "2001", "2002"]}}

I would like to populate 3 select lists 1) make 2) model and 3) year When a car make is selected (saturn), the second list should get populated with the 2 models available (sky and l-series).'

When a specific model (sky) is selected, it should populate the 3rd select list with the options for year.

I populate the first select list using the following rails snippet:

<%=  select_tag "make-select", options_for_select(@all_makes_models.to_hash.keys.sort, params[:make]), :class=>"car-make-select" %>

I am not sure how to access the ruby hash using jquery.

Trying to access ruby hash like below gives me javascript syntax error.

$('#make-select').change(function()
{       
    make = $(this).attr('value');
    models = '<%= @all_makes_models[" + make + "].to_hash.keys %>';
    alert(models);
    $('#car-models').val(models);
});

Any ideas on how to access the hash in javascript? (not js.erb)

Thanks

How about assigning all your makes and models to the 'models' javascript variable as a json object? Each time a select list changes, you can traverse your data and re-populate the form elements.

<script type="text/javascript">
    var models = <%= @all_makes_models.to_json %>;

    $(document).ready(function() {
        $(".car-selector").change(function() { 
            // Traverse JSON object, repopulate select lists.
        });
    });
</script>

If you don't want to render that much data in your view by default, you could use the same concept, but fetch the JSON data via ajax by submitting the partially completed form.

This post solved the problem for me.

As you, I was not using data from a database. Just ignore the line of the controller that makes the query and pass the params[:id] to the partial. This solution also lets you transfer data from your hash (I'd rather use an array, already sorted) to the db with minimum code modification should your app get more complicated in the future.

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