开发者

Use jQuery select an option?

<select>
            <option value="0" id="n">n</option>
            <option value="1" id="m">m</option>
</select>

In jQuery, how do I make the开发者_StackOverflow社区 option 'selected' for id=m?


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');


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");


$("#m").addAttr('selected', true)
       .siblings('option')
       .removeAttr('selected');


I agree with @coder. One slight change to his code is removing of previously selected entry. If user has already selected an option and then you want to change it to something else using jquery (unless your select box has attribute "multiple" set), you will have to un-select the user's selection option.

$("#myselect option:eq(1)").attr("selected", "selected").siblings("option").removeAttr("selected");

as mentioned by @cletus.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜