Use JQUERY/JSON to auto fill select dropdown boxes

前端 未结 2 926
南笙
南笙 2021-01-16 20:20

OK I spent spent a lot of time looking over examples but can\'t find one which helps me enough for my situation. I have a JSON file, simplified for this example:

<         


        
相关标签:
2条回答
  • 2021-01-16 20:55

    This should do the trick.

    $.each(data.Company, function(key, val) {
        $select.append('<option id="' + key + '">' + val.Position + '</option>');
    });
    
    
    
    $("#job").change(function(e) {
        $select2.empty();
        $index = $(this).children(':selected').attr('id');
            for (var k in data.Company[$index].Name) {
                $select2.append('<option id="' + k + '">' + data.Company[$index].Name[k] + '</option>');
            }
    });
    
    0 讨论(0)
  • 2021-01-16 21:10

    Try something like this. You should really have a value property for your options. I added a data-id attr to the options so I can use that to store the index of Position.

    $.each(data.Company, function(i, v) {
        // create option with value as index - makes it easier to access on change
        var options = $('<option/>', {value: v.Position, text: v.Position}).attr('data-id',i);    
        // append the options to job selectbox
        $('#job').append(options);
    });
    
    // bind change event
    $('#job').change(function() {
        // cache this
        var $el = $(this);
        // get data-id attr from selected option
        var id = $('option:selected',this).data('id');
        // empty select
        $('#name').empty();
        // get name values for selected option
        $.each(data.Company[id].Name, function(i, v) {
            // create option elements
            var options = $('<option/>', {value: v, text: v});
            // append the options to name selectbox
            $('#name').append(options);
        });    
    }).change();// trigger change() on page load to fill name selectbox​
    

    http://jsfiddle.net/wirey00/xYX8z/

    0 讨论(0)
提交回复
热议问题