<select>
<option value="0" id="n">n</option>
<option value="1" id="m">m</option>
</select>
In Jquery, how do I make the option 'selected' for id=m?
<select>
<option value="0" id="n">n</option>
<option value="1" id="m">m</option>
</select>
In Jquery, how do I make the option 'selected' for id=m?
Just set the selected
attribute on the option:
$("#m").attr("selected", true);
If you also want to deselect other options when you do this the simplest option is:
$("#m").attr("selected", true).siblings("option").removeAttr("selected");
This doesn't cover the case of fieldsets however. To cover that use something like:
$("#m").attr("selected", true).closest("select")
.find("option").removeAttr("selected");
it is not the correct way to add id for each options in the select. if i were you, i would do like below
<select id="myselect">
<option value="0">n</option>
<option value="1">m</option>
</select>
Set the element at index 1 using below
$("#myselect option:eq(1)").attr("selected", "selected");
Set an id on the select element instead:
<select id="TheDropDown">
<option value="0">n</option>
<option value="1">m</option>
</select>
Then use the val
function:
$('#TheDropDown').val('1');
$("#m").addAttr('selected', true)
.siblings('option')
.removeAttr('selected');