12

I've been working through this and I'm a little stuck. I can't seem to find a direct answer so I'm gonna ask.

I'm creating an options list from a JSON call. I've created the child elements but I can't seem to add the unique ID's (stored in the JSON) to each element. When I create the ID inside the $.each of the JSON I get the last ID from the call assigned to all the options.

Thanks

$("#fDistList").append('<option>' + item.GROUP_NAME + '</option>');
$("option").attr('id', item.ID);
atlMapper
  • 764
  • 3
  • 9
  • 24

2 Answers2

4

You could do it like this, in a single pass

$('<option/>',{
        text: item.GROUP_NAME, 
        id:item.ID
    }).appendTo('#fDistList');
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • Do you have a link for the documentation for this? I need to learn more about this single pass, its much cleaner. – atlMapper Dec 26 '12 at 17:58
  • @atlMapper, see the 2nd version of http://api.jquery.com/jquery/#jQuery2 for creating elements with a map of properties, and http://api.jquery.com/appendTo/ for appending to elements – Gabriele Petrioli Dec 26 '12 at 18:07
3

Try this

$("#fDistList").append('<option id="'+ item.ID + '">' + item.GROUP_NAME + '</option>');

When you do

$("option").attr('id', item.ID);

you are reselecting all option elements and setting their ID attribute.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • thanks, that was it...the double quotes inside the single quotes I wasn't even considering that to be an option but it makes so much sense now. – atlMapper Dec 07 '12 at 20:10