必承其重 | 欲带皇冠 2008-09-06 20:53 采纳率: 0%
浏览 498
已采纳

如何删除选择框的所有选项,然后添加一个选项并用 jQuery 选择它?

Using core jQuery, how do you remove all the options of a select box, then add one option and select it?

My select box is the following.

<Select id="mySelect" size="9" </Select>

EDIT: The following code was helpful with chaining. However, (in Internet Explorer) .val('whatever') did not select the option that was added. (I did use the same 'value' in both .append and .val.)

$('#mySelect').find('option').remove().end().append('<option value="whatever">text</option>').val('whatever');

EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. .focus() was closer, but the option did not appear selected like it does with .selected= "true". Nothing is wrong with my existing code - I am just trying to learn jQuery.

var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";

EDIT: selected answer was close to what I needed. This worked for me:

$('#mySelect').children().remove().end().append('<option selected value="whatever">text</option>') ;

But both answers led me to my final solution..

转载于:https://stackoverflow.com/questions/47824/how-do-you-remove-all-the-options-of-a-select-box-and-then-add-one-option-and-se

  • 写回答

21条回答 默认 最新

  • elliott.david 2008-09-06 21:01
    关注
    $('#mySelect')
        .find('option')
        .remove()
        .end()
        .append('<option value="whatever">text</option>')
        .val('whatever')
    ;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(20条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题