如何删除选择框的所有选项,然后添加一个选项并使用 jQuery 选择它?
-
09-06-2019 - |
题
使用核心 jQuery,如何删除选择框的所有选项,然后添加一个选项并选择它?
我的选择框如下。
<Select id="mySelect" size="9" </Select>
编辑:以下代码对链接很有帮助。但是,(在 Internet Explorer 中) .val('whatever')
没有选择添加的选项。(我确实在两者中使用了相同的“值” .append
和 .val
.)
$('#mySelect').find('option').remove().end().append('<option value="whatever">text</option>').val('whatever');
编辑:为了让它模仿此代码,每当重置页面/表单时,我都会使用以下代码。该选择框由一组单选按钮填充。 .focus()
更接近,但该选项并未像它那样显示为选中 .selected= "true"
. 。我现有的代码没有任何问题 - 我只是想学习 jQuery。
var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";
编辑:所选答案接近我所需要的。这对我有用:
$('#mySelect').children().remove().end().append('<option selected value="whatever">text</option>') ;
但这两个答案都引导我找到了最终的解决方案。
解决方案
$('#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;
我在 IE7 中遇到了一个错误(在 IE6 中工作正常),使用上面的 jQuery 方法可以清除 选择 在 DOM 中但不在屏幕上。使用 IE 开发工具栏我可以确认 选择 已经被清除并有新物品,但视觉上 选择 仍然显示旧项目 - 即使您无法选择它们。
修复方法是使用标准 DOM 方法/属性(如海报原文所示)来清除而不是 jQuery - 仍然使用 jQuery 来添加选项。
$('#mySelect')[0].options.length = 0;
如果您的目标是从选择中删除除第一个选项之外的所有选项(通常是“请选择一个项目”选项),您可以使用:
$('#mySelect').find('option:not(:first)').remove();
不确定“添加一个并选择它”到底是什么意思,因为无论如何它都会被默认选择。但是,如果您要添加多个,那就更有意义了。怎么样:
$('select').children().remove();
$('select').append('<option id="foo">foo</option>');
$('#foo').focus();
回复“编辑”: :您能否澄清“此选择框由一组单选按钮填充”的含义?A <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>");
感谢我收到的答案,我能够创建如下所示的内容,以满足我的需求。我的问题有点含糊。感谢您的关注。我的最后一个问题是通过在我想要选择的选项中包含“选定”来解决的。
$(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>
首先清除除第一个选项之外的所有现有选项(--Select--)
使用循环一一附加新选项值
$('#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)); }
将 html 更改为新数据怎么样?
$('#mySelect').html('<option value="whatever">text</option>');
另一个例子:
$('#mySelect').html('
<option value="1" selected>text1</option>
<option value="2">text2</option>
<option value="3" disabled>text3</option>
');
其他方式:
$('#select').empty().append($('<option>').text('---------').attr('value',''));
在这个链接下,有一些好的做法 https://api.jquery.com/select/
我在网上发现了类似下面的内容。像我这样的情况有数千个选项,这比 .empty()
或者 .find().remove()
来自 jQuery。
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;
}
更多信息 这里.
基于莫雷托的答案,这更容易阅读和理解:
$('#mySelect').find('option').not(':first').remove();
要删除除具有特定值的选项之外的所有选项,您可以使用以下命令:
$('#mySelect').find('option').not('[value=123]').remove();
如果要添加的选项已经存在,那就更好了。
$("#id option").remove();
$("#id").append('<option value="testValue" >TestText</option>');
第一行代码将删除选择框的所有选项,因为没有提到选项查找条件。
第二行代码将添加具有指定值(“testValue”)和文本(“TestText”)的选项。
使用jquery 支柱() 清除所选选项
$('#mySelect option:selected').prop('selected', false);
这会将现有的 mySelect 替换为新的 mySelect。
$('#mySelect').replaceWith('<Select id="mySelect" size="9">
<option value="whatever" selected="selected" >text</option>
</Select>');
你可以简单地通过替换 html 来完成
$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');
希望它能起作用
$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));
- 保存要附加到对象中的选项值
- 清除 select 标签中的现有选项
- 迭代列表对象并将内容附加到预期的选择标签
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>
我在 select2 中看到了这段代码https://select2.org/programmatic-control/add-select-clear-items#clearing-selections
$('#mySelect).val(null).trigger('change');
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('');