Select added listitem of select
I have a select:
<select id="club">
<option> </option>
<option value=bla1>bla1</option>
<option value=bla2>bla2</option>
</select>
I added an item as first item to the <select>
with this code, which works fine:
$("#club option").eq(0).before("<option value=1>test</option>").css("background-color", "#F2EE72");
But the empty option is still selected, and I want the just added item to be selected, so it's visible as defaul开发者_开发百科t item in the listbox. How can I do that? Thanks!
Since you add the new option node before the eq(0)
, you simply need to chain a prev()
to access it.
Like this:
$("#club option").eq(0).before('<option value="1">test</option>').css("background-color", "#F2EE72").prev().prop('selected',true);
Example: http://jsfiddle.net/AlienWebguy/9EVjn/1/
Try:
1)
$("#club option").eq(0).before("<option selected value=1>test</option>").css("background-color", "#F2EE72");
or
2)
$("#club option").eq(0).before("<option value=1>test</option>").css("background-color", "#F2EE72");
$("#club").val(1);
精彩评论