jQuery how to remove :selected attribute and add new one properly
How do I remove :selected开发者_运维问答
attribute and add new one?
You want something like
$('#mySelect option:selected').removeAttr('selected');
$('#mySelect option:nth-child(5)').attr('selected','selected');//select the one you want
btw, are you talking about a select list single (e.g. dropdown)?... or a select multiple? - you'll need to adjust accordingly if this is a multi-select.
I updated the nth child selector... when setting the selected attribute as square bracket notation [4] doesn't work in the selector.
If you're talking about a <select>
just set the value using .val()
like this:
$('#mySelect').val('new value');
This automatically selects the <option>
with that value.
If it is a multi-select and you need to remove the selected
from all rows, you can use the following:
$("#mySelect option:selected").each(function () {
$(this).removeAttr('selected');
});
The first clause fetches all of the selected options, while the each
iterates through them, and the removeAttr eliminates the 'selected'.
$('#mySelect').val('new value'); This automatically selects the with that value.
But in the case of the value is not exists before in select options no value will be selected, So make sure the value already exists in select options.
精彩评论