喵-见缝插针 2008-09-06 20:53 采纳率: 0%
浏览 374
已采纳

如何删除选择框的所有选项,然后添加一个选项并用 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

  • 写回答

20条回答 默认 最新

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

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题