ozil
ozil

Reputation: 7117

How to dynamically create select with selected option

I am making select tag dynamically like this, what I want to make third option selected

var dropDownList = $('<select />', {
  'id': 'my id',                 // some id i want to apply
  'class': 'my class',           //some class i want to aply
  });  
for (iLoop = 0; iLoop < myarray.length ; ++iLoop) {
  if(iLoop ==2){
    $('<option />', {
      'value': myarray[iLoop ].value,
      'text':  myarray[iLoop ].text,
      'selected': ??      // true/false
    }).appendTo(dropDownList);
  }
  else{
    $('<option />', {
      'value': myarray[iLoop ].value,
      'text':  myarray[iLoop ].text,
    }).appendTo(dropDownList);
  }
}  

Beside i dont want to make like this

var selectElement='<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel" selected>Opel</option>
  <option value="audi">Audi</option>
</select>';

Upvotes: 1

Views: 1454

Answers (2)

Rahaman
Rahaman

Reputation: 333

for (iLoop = 0; iLoop < myarray.length ; ++iLoop)

If you are writing a for loop don't calculate array length inside the loop. Better to use as below

var myarrayLength = myarray.length;
for (iLoop = 0; iLoop < myarrayLength ; ++iLoop)

don't compare like below. If array size is n than this comparison will be happen n times

'selected': (iLoop == 2 ? true : false)

It's more better to Use for in loop instead of for loop.

for (iLoop in myarray) {
    $('<option />', { 'value': myarray[iLoop ].value,
                      'text':  myarray[iLoop ].text,
                     }).appendTo(dropDownList);
}  

$("#time_entry_activity_id option:eq(3)").attr('selected', 'selected');

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77482

Use attribute selected, like so

for (iLoop = 0; iLoop < myarray.length ; ++iLoop) {
    $('<option />', {
        'value': myarray[iLoop ].value,
        'text':  myarray[iLoop ].text,
        'selected': (iLoop == 2 ? true : false)
    }).appendTo(dropDownList);
}  

Example

Upvotes: 2

Related Questions