Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

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

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

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

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.

(但是,(在Internet Explorer中) .val('whatever')没有选择添加的选项。)

(I did use the same 'value' in both .append and .val .)

((我在.append.val中都使用了相同的'value'。))

$('#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" .

(.focus()更接近,但该选项似乎没有像.selected= "true"那样被选中。)

Nothing is wrong with my existing code - I am just trying to learn jQuery.

(我现有的代码没有任何问题 - 我只是想学习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..

(但这两个答案都让我得到了最后的解决方案..)

  ask by Jay Corbett translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$('#mySelect')
    .find('option')
    .remove()
    .end()
    .append('<option value="whatever">text</option>')
    .val('whatever')
;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...