How do you remove all the options of a select box

2019-01-01 14:11发布

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

21条回答
牵手、夕阳
2楼-- · 2019-01-01 14:26
$("#control").html("<option selected=\"selected\">The Option...</option>");
查看更多
春风洒进眼中
3楼-- · 2019-01-01 14:27

I had a bug in IE7 (works fine in IE6) where using the above jQuery methods would clear the select in the DOM but not on screen. Using the IE Developer Toolbar I could confirm that the select had been cleared and had the new items, but visually the select still showed the old items - even though you could not select them.

The fix was to use standard DOM methods/properites (as the poster original had) to clear rather than jQuery - still using jQuery to add options.

$('#mySelect')[0].options.length = 0;
查看更多
伤终究还是伤i
4楼-- · 2019-01-01 14:28
$('#mySelect')
    .empty()
    .append('<option value="whatever">text</option>')
    .find('option:first')
    .attr("selected","selected")
;
查看更多
看淡一切
5楼-- · 2019-01-01 14:28

Uses the jquery prop() to clear the selected option

$('#mySelect option:selected').prop('selected', false);
查看更多
骚的不知所云
6楼-- · 2019-01-01 14:31

How about just changing the html to new data.

$('#mySelect').html('<option value="whatever">text</option>');

Another example:

$('#mySelect').html('
    <option value="1" selected>text1</option>
    <option value="2">text2</option>
    <option value="3" disabled>text3</option>
');
查看更多
旧人旧事旧时光
7楼-- · 2019-01-01 14:32

You can do simply by replacing html

$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');
查看更多
登录 后发表回答