简体   繁体   English

如何删除选择框的所有选项,然后添加一个选项并使用 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中使用了相同的“值”。)

$('#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..但是这两个答案都让我找到了最终的解决方案..

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

为什么不只使用普通的javascript?

document.getElementById("selectID").options.length = 0;

如果您的目标是从选择中删除除第一个选项之外的所有选项(通常是“请选择一个项目”选项),您可以使用:

$('#mySelect').find('option:not(:first)').remove();

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.我在 IE7 中有一个错误(在 IE6 中工作正常),使用上述 jQuery 方法会清除 DOM 中的选择,但不会清除屏幕上的选择。 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.使用 IE 开发工具栏,我可以确认选择已被清除并有新项目,但在视觉上,选择仍然显示旧项目 - 即使您无法选择它们。

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.解决方法是使用标准 DOM 方法/属性(如海报原件那样)来清除而不是 jQuery - 仍然使用 jQuery 添加选项。

$('#mySelect')[0].options.length = 0;

Not sure exactly what you mean by "add one and select it", since it will be selected by default anyway.不确定“添加一个并选择它”的确切含义,因为无论如何默认情况下都会选择它。 But, if you were to add more than one, it would make more sense.但是,如果您要添加多个,那就更有意义了。 How about something like:怎么样:

$('select').children().remove();
$('select').append('<option id="foo">foo</option>');
$('#foo').focus();

Response to "EDIT" : Can you clarify what you mean by "This select box is populated by a set of radio buttons"?对“编辑”的回应:您能否澄清“此选择框由一组单选按钮填充”的意思? A <select> element cannot (legally) contain <input type="radio"> elements. <select>元素不能(合法地)包含<input type="radio">元素。

$('#mySelect')
    .empty()
    .append('<option value="whatever">text</option>')
    .find('option:first')
    .attr("selected","selected")
;
$("#control").html("<option selected=\"selected\">The Option...</option>");

Just one line to remove all options from the select tag and after you can add any options then make second line to add options.只需一行即可从选择标签中删除所有选项,然后您可以添加任何选项,然后在第二行添加选项。

$('.ddlsl').empty();

$('.ddlsl').append(new Option('Select all', 'all'));

One more short way but didn't tried还有一种捷径,但没试过

$('.ddlsl').empty().append(new Option('Select all', 'all'));

Thanks to the answers I received, I was able to create something like the following, which suits my needs.多亏了我收到的答案,我才能够创造出符合我需要的类似以下内容。 My question was somewhat ambiguous.我的问题有点模棱两可。 Thanks for following up.感谢您的跟进。 My final problem was solved by including "selected" in the option that I wanted selected.我的最后一个问题是通过在我想要选择的选项中包含“选择”来解决的。

 $(function() { $('#mySelect').children().remove().end().append('<option selected value="One">One option</option>') ; // clear the select box, then add one option which is selected $("input[name='myRadio']").filter( "[value='1']" ).attr( "checked", "checked" ); // select radio button with value 1 // Bind click event to each radio button. $("input[name='myRadio']").bind("click", function() { switch(this.value) { case "1": $('#mySelect').find('option').remove().end().append('<option selected value="One">One option</option>') ; break ; case "2": $('#mySelect').find('option').remove() ; var items = ["Item1", "Item2", "Item3"] ; // Set locally for demo var options = '' ; for (var i = 0; i < items.length; i++) { if (i==0) { options += '<option selected value="' + items[i] + '">' + items[i] + '</option>'; } else { options += '<option value="' + items[i] + '">' + items[i] + '</option>'; } } $('#mySelect').html(options); // Populate select box with array break ; } // Switch end } // Bind function end ); // bind end }); // Event listener end
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label>One<input name="myRadio" type="radio" value="1" /></label> <label>Two<input name="myRadio" type="radio" value="2" /></label> <select id="mySelect" size="9"></select>

I've found on the net something like below.我在网上找到了类似下面的东西。 With a thousands of options like in my situation this is a lot faster than .empty() or .find().remove() from jQuery.在我的情况下,有数千个选项,这比 jQuery 中的.empty().find().remove()

var ClearOptionsFast = function(id) {
    var selectObj = document.getElementById(id);
    var selectParentNode = selectObj.parentNode;
    var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
    selectParentNode.replaceChild(newSelectObj, selectObj);
    return newSelectObj;
}

More info here .更多信息在这里

How about just changing the html to new data.将html更改为新数据怎么样。

$('#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>
');
  1. First clear all exisiting option execpt the first one(--Select--)首先清除所有现有选项,除了第一个选项(--Select--)

  2. Append new option values using loop one by one使用循环一一追加新选项值

    $('#ddlCustomer').find('option:not(:first)').remove(); for (var i = 0; i < oResult.length; i++) { $("#ddlCustomer").append(new Option(oResult[i].CustomerName, oResult[i].CustomerID + '/' + oResult[i].ID)); }

Another way:另一种方式:

$('#select').empty().append($('<option>').text('---------').attr('value',''));

Under this link, there are good practices https://api.jquery.com/select/在这个链接下,有很好的做法https://api.jquery.com/select/

$("#id option").remove();
$("#id").append('<option value="testValue" >TestText</option>');

The first line of code will remove all the options of a select box as no option find criteria has been mentioned.第一行代码将删除选择框的所有选项,因为没有提到选项查找条件。

The second line of code will add the Option with the specified value("testValue") and Text("TestText").第二行代码将添加具有指定值(“testValue”)和文本(“TestText”)的选项。

Building on mauretto's answer, this is a little easier to read and understand:基于 mauretto 的回答,这更容易阅读和理解:

$('#mySelect').find('option').not(':first').remove();

To remove all the options except one with a specific value, you can use this:要删除除具有特定值的选项之外的所有选项,您可以使用以下命令:

$('#mySelect').find('option').not('[value=123]').remove();

This would be better if the option to be added was already there.如果要添加的选项已经存在,这会更好。

This will replace your existing mySelect with a new mySelect.这将用新的 mySelect 替换现有的 mySelect。

$('#mySelect').replaceWith('<Select id="mySelect" size="9">
   <option value="whatever" selected="selected" >text</option>
   </Select>');

使用 jquery prop()清除选中的选项

$('#mySelect option:selected').prop('selected', false);

You can do simply by replacing html你可以简单地通过替换 html

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

Cleaner give me Like it清洁工给我点赞

   let data= []

   let inp = $('#mySelect')
        inp.empty()

        data.forEach(el=> inp.append(  new Option(el.Nombre, el.Id) ))
  • save the option values to be appended in an object保存要附加到对象中的选项值
  • clear existing options in the select tag清除选择标签中的现有选项
  • iterate the list object and append the contents to the intended select tag迭代列表对象并将内容附加到预期的选择标签

 var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'}; $('#selectID').empty(); $.each(listToAppend, function(val, text) { $('#selectID').append( new Option(text,val) ); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I saw this code in Select2 - Clearing Selections我在 Select2 - Clearing Selections中看到了这段代码

$('#mySelect').val(null).trigger('change');

This code works well with jQuery even without Select2即使没有 Select2,此代码也适用于 jQuery

I used vanilla javascript我使用香草 javascript

let select = document.getElementById("mySelect");
select.innerHTML = "";

Hope it will work希望它会起作用

$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));
var select = $('#mySelect');
select.find('option').remove().end()
.append($('<option/>').val('').text('Select'));
var data = [{"id":1,"title":"Option one"}, {"id":2,"title":"Option two"}];
for(var i in data) {
    var d = data[i];
    var option = $('<option/>').val(d.id).text(d.title);
    select.append(option);
}
select.val('');

Try尝试

mySelect.innerHTML = `<option selected value="whatever">text</option>`

 function setOne() { console.log({mySelect}); mySelect.innerHTML = `<option selected value="whatever">text</option>`; }
 <button onclick="setOne()" >set one</button> <Select id="mySelect" size="9"> <option value="1">old1</option> <option value="2">old2</option> <option value="3">old3</option> </Select>

最短的答案:

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

Try尝试

$('#mySelect')
.html('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected");

OR或者

$('#mySelect').html('<option value="4">Value 4</option>
 <option value="5">Value 5</option>
<option value="6">Value 6</option>
<option value="7">Value 7</option>
<option value="8">Value 8</option>')
.find('option:first')
.prop("selected",true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM