简体   繁体   中英

Populating select option dynamically with jquery

There will be two drop down lists,

First have the list of mobile vendor, and the second have the list of models per vendor.

When one select a vendor from the first drop down list, the second drop down list should populate with relevant model for that vendor dynamically. This is for mobile web site, it's better to use jquery-mobile

The option values for the second will in a json map.

  <select class="mobile-vendor">
    <option value="motorola">Motorola</option>
    <option value="nokia">Nokia</option>
    <option value="android">Android</option>
  </select>

 selectValues = {"nokia"   : {"N97":"download-link", 
                              "N93":"download-link"}, 
                 "motorola": {"M1":"download-link",
                              "M2":"download-link"}}

<select class="model">
    <option></option>
</select>

For example, if the user selects nokia in the first drop down list, the second drop down list should have N97, N93 as the options.

EDIT: New javascript to take into account your updated json structure:

$(function() {
    var selectValues = {
        "nokia": {
            "N97": "http://www.google.com",
            "N93": "http://www.stackoverflow.com"
        },
        "motorola": {
            "M1": "http://www.ebay.com",
            "M2": "http://www.twitter.com"
        }
    };

    var $vendor = $('select.mobile-vendor');
    var $model = $('select.model');
    $vendor.change(function() {
        $model.empty().append(function() {
            var output = '';
            $.each(selectValues[$vendor.val()], function(key, value) {
                output += '<option>' + key + '</option>';
            });
            return output;
        });
    }).change();

    // bonus: how to access the download link
    $model.change(function() {
        $('#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
    });
});

Working example is available in jsFiddle .

Note that this should work with jQuery mobile just fine.

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