Populating select option dynamically with jquery

后端 未结 1 1587
遇见更好的自我
遇见更好的自我 2020-12-10 13:55

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 t

相关标签:
1条回答
  • 2020-12-10 14:26

    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.

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