12

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?

kronn
  • 925
  • 11
  • 31
peter cooke
  • 987
  • 3
  • 10
  • 28
  • 1
    What are you having problems with? – Blender Feb 17 '13 at 22:54
  • 1
    FYI - Don't say select statement, that sounds like you're talking about making a database query. – Klik Feb 17 '13 at 22:55
  • When I saw 'select statement' I also thought you were building a SQL query on the client side which is a very bad idea. A better title probably would have been "Dynamically creating a select element". It is also convention in JS to only start variable names with a capital letter if they are constructor functions, using it for a normal variable will be confusing for people reading your code in the future; you should rename `Organizations` to `organizations`. – Useless Code Feb 17 '13 at 23:35
  • Looking at the code again, `Organizations` isn't a valid JS object, that code should not work. It looks more like it should be an array which would start/end with `[` and `]`, not `{` and `}`, and would require a comma between each item. If it is supposed to be an object it would require a label and a `:` to the left of each sub-object and a comma after all but the last sub-item. – Useless Code Feb 17 '13 at 23:48
  • I am trying to build an HTML select dropdown. In Dojo I used a datastore that points at some dom object, and then use some dojo select tag that for all the things in dom object builds a an html select widget – peter cooke Feb 22 '13 at 03:03

1 Answers1

5
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
Klik
  • 1,757
  • 1
  • 21
  • 38