stackato
stackato

Reputation: 1145

JS/HTML -- dynamically create select element with options

I have an ExtJS application. In my grid I am using the columns renderer function to return the select element drop down. My current implementation is below:

//grid col renderer fn

renderer:function(val, meta, rec) {
  return [
    '<select id="states"  value="" disabled selected>Select...</option>'+             
      '<option value="CA">California</option>'+
      '<option value="NY">New York</option>'+
      '<option value="TX">Texas</option>'+
      '<option value="FL">Florida</option>'+
      '<option value="NJ">New Jersey</option>'+               
    '</select>'
  ];

and this all works fine but now the list of options is going to be dynamic. The sample JSON is below:

"states":[{"value":"CA","name":"California"},{"value":"Ny", "name":"New York"},{...}]

So I want to iterate the "states" array and create an option el for each object then push that option into the select element.

Thanks

Upvotes: 0

Views: 3255

Answers (2)

Rayon
Rayon

Reputation: 36609

Try this:

var this_select_content = '<select id="states">';
for(var i=0; i < states.length; i++){
    this_select_content += '<option value="' + states[i]['value'] + '">' + states[i]['name'] + '</option>';
}
this_select_content +='</select>'
$("#states").empty().append(this_select_content);
Basically you need to iterate through the array of states..

Upvotes: 1

Tariq
Tariq

Reputation: 2871

Try this:

this_select_content = '';
for(var i=0; i < states.length; i++){
    var this_select_content += '<option value="' + states[i]['value'] + '">' + states[i]['name'] + '</option>';
}
$("#states").empty().append(this_select_content);

Upvotes: 2

Related Questions