如何删除选择框的所有选项,然后添加一个选项并使用jQuery选择它? [英] How do you remove all the options of a select box and then add one option and select it with jQuery?

查看:114
本文介绍了如何删除选择框的所有选项,然后添加一个选项并使用jQuery选择它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的选择框如下。

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

编辑:以下代码对链接有帮助。但是,(在Internet资源管理器中) .val('whatever')未选择已添加的选项。 (我确实在 .append .val 中使用相同的'值'。)

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

编辑:试图让它模仿这段代码,每当页面/表格使用以下代码重置。此选择框由一组单选按钮填充。 .focus()离得更近了,但该选项没有像那样被选中。选择=真 。我的现有代码没有任何问题 - 我只是想学习jQuery。

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

编辑:选择的答案接近我的需要。这对我有用:

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..

推荐答案

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

这篇关于如何删除选择框的所有选项,然后添加一个选项并使用jQuery选择它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆