Reputation: 7117
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
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
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);
}
Upvotes: 2