Reputation: 4748
I just got this chained select box working that uses JSON data to populate the options. Fiddle. The data is hard-coded, but I want to load the data using the $.getJSON()
method, but I can't get the code right. I think the suggest.json file is triggered, but something else seems to be causing the problem. Would anyone please show me how to fix the problem?
I got the The Drop down Box from this site
The original code:
<script type="text/javascript">
var s = '[{"Box1":"Africa","CODE":1,"ID":"A"},{"Box1":"Asia","CODE":2,"ID":"B"},{"Box1":"South America","Code":3,"ID":"C"}]';
var jsonData = $.parseJSON(s);
var $select = $('#mySelectID');
$(jsonData).each(function (index, o) {
var $option = $("<option/>").attr("value", o.CODE).text(o.Box1 + "|" + o.ID);
$select.append($option);
});
jQuery("#mySelectID").dynamicDropdown({"delimiter":"|"});
</script>
Here's my failed attempt:
<script type="text/javascript">
$.getJSON('suggest.json', function(data){
var $select = $('#mySelectID');
$.each(data, function (index, o) {
var $option = $("<option/>").attr("value", o.CODE).text(o.Box1 + "|" + o.ID);
$select.append($option);
});
});
jQuery("#mySelectID").dynamicDropdown({"delimiter":"|"});
</script>
Suggest.JSON:
[{"Box1":"Africa","CODE":1,"ID":"A"},{"Box1":"Asia","CODE":2,"ID":"B"},{"Box1":"South America","Code":3,"ID":"C"}]
Upvotes: -1
Views: 206
Reputation: 17899
The problem is that you haved to call $("#mySelectID").dynamicDropdown({"delimiter":"|"});
only when getJSON return you the data.
According to your code, just swap the plugin call :
$(document).ready(function(){
$.getJSON('my.json', function(data){
var $select = $('#mySelectID');
$.each(data, function (index, o) {
var $option = $("<option/>").attr("value", o.CODE).text(o.Box1 + "|" + o.ID);
$select.append($option);
});
$("#mySelectID").dynamicDropdown({"delimiter":"|"});
});
});
By the way, you have an error with your json : the last item (South America) have "Code" and note CODE" according to the others
Upvotes: 1