Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically building select statement from DOM data element [duplicate]

I need to dynamically build a select dropdown based on form data provided an ajax query. my DOM contains an element "organizations" with 4 children. The children with an org id and org name

Organizations = {
    { id="2", name="Systems"}
    { id="4", name="Network"}
    { id="5", name="Operations"}
    { id= "7", name="Security"}
}

I need to build the following select clause

<select name='organization'>
    <option value="2">Systems</option>
    <option value="4">Network</option>
    <option value="5">Operations</option>
</select>

How do I dynamically build the select statement?

like image 200
peter cooke Avatar asked Feb 17 '13 22:02

peter cooke


1 Answers

Organizations = {
     { id="2", name="Systems"}
     { id="4", name="Network"}
     { id="5", name="Operations"}
     { id= "7", name="Security"}
}

Given the above object:

var $el = $('<select></select>');  //create a new DOM Element with jQuery syntax
for (i in Organizations) { //iterate through the object and append options
  $el.append('<option value="' + Organizations[i]['id'] + '">' + Organizations[i]['name'] + '</option>');
}

Then append the created element to somewhere...

$('body').append($el);  //should work
like image 80
Klik Avatar answered Nov 07 '22 20:11

Klik