Original Fiddle using the first JSON file
Failed Fiddle using the second JSON file.
I have trouble using split and $.each function to return each small choice from an array.
I'm using a chained select box via AJAX from this site. It requires a markup like this to build chained select boxes:
<select>
<option value="mustang2000">Ford » Mustang » 2000</option>
<option value="mustang2005">Ford » Mustang » 2005</option>
<option value="focus">Ford » Focus » 2010</option>
<option value="alero">Oldsmobile » Alero » 1993</option>
</select>
Normally, the JSON file for the options would look like this:
First JSON file
[
{
"bigcat": "Sport",
"cat": "mainstream",
"choice": "football"
},
{
"bigcat": "Sport",
"cat": "mainstream",
"choice": "basketball"
},
{
"bigcat": "Sport",
"cat": "niche",
"choice": "MMA"
},
{
"bigcat": "Sport",
"cat": "niche",
"choice": "wrestling"
}
]
I want to stuff all the choices of the same category into one big choice using "|" as separators, like this:
Second JSON file
[
{
"bigcat": "Sport",
"cat": "mainstream",
"choice": "football|basketball"
},
{
"bigcat": "Sport",
"cat": "niche",
"choice": "wrestling|racing"
}
]
and in the script use split and $.each function to return each small choice
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FqMlPxn%22&format=json&diagnostics=true&callback=",
success: function(data){
var $select = $('select');var $option="";
$.each(data.query.results.json.json, function (index, i) {
smallchoice = i.choice.split(',');
$.each(smallchoice,function(i,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "@" +( i.cat || "") +"@" + smallchoice);
});
$select.append($option);
});
$select.dynamicDropdown({"delimiter":"@"});
}
});
But I have no idea how to assign bigcat and cat to each small choice. Can anyone give me suggestions?
dataTypeisjsonit will parse it for you so yourdatais an object.function(i,smallchoice)when you had already declared the same variables few lines above. Change that for something else, likefunction(j, choice)and already I see something that's not "undefined"