Dynamically building a select expression from a DOM data element
I need to dynamically build a select dropdown based on the form data provided by an ajax request. my DOM contains an "organization" element with 4 children. Children with id org and name org
Organizations = {
{ id="2", name="Systems"}
{ id="4", name="Network"}
{ id="5", name="Operations"}
{ id= "7", name="Security"}
}
I need to create 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 a select statement?
+3
source to share
1 answer
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 add the created item somewhere ...
$('body').append($el); //should work
+3
source to share