populate select boxes from json string using jquery
I have a list of select boxes with incremental numbers to identify then e.g.
<select id="my-select-0">
<option value="1">first option</option>
<option value="2">first option</option>
< option value="3">first option</option>
</select>
<select id="my-select-1">
<option value="1">first option</option>
<option value="2">first option</option>
<option value="3">first option</option>
</select>
<select id="my-select-2">
<option value="1">first option</option>
<option value="2">first option</option>
<option value="3">first option</option>
</select>
I have a json s开发者_开发知识库tring which I want to use to pre populate these selects e.g.
json = "[{'my-select': 1},
{'my-select': 3}]";
in the example above my-select-0
would be set to 1 and my-select-1
is set to 3.
How would I go about doing this in JQuery?
Thanks
I'm not sure exactly what you're after, but if you change the JSON to be valid (double quotes) you can do it using $.parseJSON()
and looping through, like this:
var json = '[{"my-select": 1}, {"my-select": 3}]';
var selects = $("[id^=my-select]"); //a class maybe? not sure of your options
$.each($.parseJSON(json), function(i, v) {
selects.eq(i).val(v['my-select']);
});
You can see a working demo here
Update: Since you control how this is rendered in the page just remove the initial quotes it's wrapped in, like this:
var json = [{'my-select': 1}, {'my-select': 3}];
var selects = $("[id^=my-select]");
$.each(json, function(i, v) {
selects.eq(i).val(v['my-select']);
});
You can see it working here, JSON is exactly what it's name says, object notation...so just use it that way, don't make it a string, just output/declare it directly as a javascript object...in this case it's an array you can loop through, and it's of course faster without all that extra work.
精彩评论