Setting the selected attribute for an option element for real jQuery use

I am creating a select list with option elements in jQuery. A simplified expression looks like this:

var sel = $("<select>"); $.each(data, function(i, v){ $("<option>").attr({ "value": i }).html(v).appendTo(sel); }); 

Then I want to select an option. Usually I would do something like:

 $(sel).val(1); 

But then the option does not have the selected attribute.

$(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 work:

 $.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?

+5
source share
1 answer

You can use your own setAttribute() method . I believe jQuery confuses differences between attributes and properties.

This gets the <option> by index from the <select> options collection element and sets the attribute:

 sel[0].options[1].setAttribute('selected','selected'); 

Or it uses jQuery to set the value first, then returns and gets the correct option using the native selectedIndex property.

 sel.val(1); sel[0].options[sel[0].selectedIndex].setAttribute('selected','selected'); 

EDIT: Disable the theme a bit, but you can create <option> elements a little differently:

 $("<option>",{ value: i, html: v }).appendTo(sel); 

Starting with jQuery 1.4, you can send a set of values ​​that you want to set for a new element.

+7
source

All Articles