Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32468

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.

Upvotes: 12

Views: 34348

Answers (1)

GregL
GregL

Reputation: 38121

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.

Upvotes: 21

Related Questions