I am generating a select list with option elements in jQuery. Simplified it looks like this:
var sel = $("<select>");
$.each(data, function(i, v){
$("<option>").attr({ "value": i }).html(v).appendTo(sel);
});
Then I want an option to be selected. Normally I would do something like:
$(sel).val(1);
But then the option does not have the selected attribute present.
$(sel).html()
gives something like:
<option value="1">1</option>
<option value="2">2</option>
and this is what I expected:
<option value="1" selected="selected">1</option>
<option value="2">2</option>
I tried this approach (same result as using .val()):
$.each(data, function(i, v){
var attrs = { "value": i };
if(i == 1){
attrs.selected = "selected";
}
$("<option>").attr(attrs).html(v).appendTo(sel);
});
but the only way I found working is:
$.each(data, function(i, v){
var el = "<option>";
if(i == 1){
el = '<option selected="selected"></option>';
}
$(el).attr({ "value": i }).html(v).appendTo(sel);
});
Is there any other or better way?