Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery or JS create child element and assign an ID [duplicate]

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);
like image 545
atlMapper Avatar asked Dec 07 '12 19:12

atlMapper


2 Answers

You could do it like this, in a single pass

$('<option/>',{
        text: item.GROUP_NAME, 
        id:item.ID
    }).appendTo('#fDistList');
like image 161
Gabriele Petrioli Avatar answered Oct 01 '22 09:10

Gabriele Petrioli


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.

like image 40
Daniel A. White Avatar answered Oct 01 '22 09:10

Daniel A. White