Hari Hari - 4 months ago 16
jQuery Question

Population of dropdown showing no data

I have wrote a script where i need to populate a dropdown based on selection of another dropdown using j-query, but when i select the first dropdown the other dropdown is showing no data,please help pardon me if i went wrong somewhere.!

script.html

<div class="form-group">
<select id="json-one" class="form-control">
<option selected="" value="base">Please Select</option>
<option value="beverages">Beverages</option>
<option value="snacks">Snacks</option>
</select>
</div>

<div class="form-group">
<select id="json-two" class="form-control">
<option>Please choose from above</option>
</select>
</div>


<script>
$("#json-one").change(function() {

var $dropdown = $(this);

$.getJSON("data.json", function(data) {

var key = $dropdown.val();
var vals = [];

switch (key) {
case 'beverages':
vals = data.beverages.split(",");
break;
case 'snacks':
vals = data.snacks.split(",");
break;
case 'base':
vals = ['Please choose from above'];
}

var $jsontwo = $("#json-two");
$jsontwo.empty();
$.each(vals, function(index, value) {
$jsontwo.append("<option>" + value + "</option>");
});

});
});

</script>

Answer

I have checked the same code as yours in this fiddle.

The only difference is I am not loading json asynchronously. So you need to check the loading of json part, or whether file is present at the location or not.

    <div class="form-group">
    <select id="json-one" class="form-control">  
        <option selected="" value="base">Please Select</option>  
        <option value="beverages">Beverages</option>  
        <option value="snacks">Snacks</option>  
    </select>  
</div>

<div class="form-group">
    <select id="json-two" class="form-control">  
        <option>Please choose from above</option>  
    </select>  
</div>

var data = {
"beverages":"tea,coffee",
"snacks":"namkeen,biscuits"
};
$("#json-one").change(function() {

                var $dropdown = $(this);

                //$.getJSON("data.json", function(data) {

                    var key = $dropdown.val();
                    var vals = [];

                    switch(key) {
                        case 'beverages':
                            vals = data.beverages.split(",");
                            break;
                        case 'snacks':
                            vals = data.snacks.split(",");
                            break;
                        case 'base':
                            vals = ['Please choose from above'];
                    }

                    var $jsontwo = $("#json-two");
                    $jsontwo.empty();
                    $.each(vals, function(index, value) {
                        $jsontwo.append("<option>" + value + "</option>");
                    //});

                });
            });

Let me know if you need anything else.

Comments