tags:

views:

145

answers:

1

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 string 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

+1  A: 

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.

Nick Craver
thanks this is exactly what I want. However I am using jquery 1.3.0 which doesn't have the parseJSON function. Is your solution possible using 1.3.0? Thanks
John
@John - How are you getting the JSON string? is it rendered into the page, or fetched via AJAX?
Nick Craver
rendered into the page just as you have it above i.e. json = ???The string itself is dynamically created using server side scripting.
John
@John - I updated the answer given the new info, the approach is much simpler and will work in jQuery 1.3.0 as well, let me know if you have any trouble :)
Nick Craver
thanks works perfectly
John