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

发布于 2024-07-05 00:36:55 字数 1021 浏览 9 评论 0原文

使用核心 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>') ;

但这两个答案都引导我找到了最终的解决方案。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(28

落墨 2024-07-12 00:36:56
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('');
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('');
ゃ懵逼小萝莉 2024-07-12 00:36:56

尝试

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

$('#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);

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);
终止放荡 2024-07-12 00:36:56

尝试

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>

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>

奈何桥上唱咆哮 2024-07-12 00:36:56

最短的答案:

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

The shortest answer:

$('#mySelect option').remove().append('<option selected value="whatever">text</option>');
眼泪也成诗 2024-07-12 00:36:55

我使用了普通的 javascript

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

I used vanilla javascript

let select = document.getElementById("mySelect");
select.innerHTML = "";
请远离我 2024-07-12 00:36:55

希望它能起作用

$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));

Hope it will work

$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));
画中仙 2024-07-12 00:36:55
  • 保存要附加到对象中的选项值
  • 清除选择标记中的现有选项
  • 迭代列表对象并将内容附加到预期的选择标记
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>

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

一梦浮鱼 2024-07-12 00:36:55

清洁工给我点个赞

   let data= []

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

        data.forEach(el=> inp.append(  new Option(el.Nombre, el.Id) ))

Cleaner give me Like it

   let data= []

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

        data.forEach(el=> inp.append(  new Option(el.Nombre, el.Id) ))
一腔孤↑勇 2024-07-12 00:36:55

我在 Select2 中看到了这段代码 -
清除选择

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

即使没有 jQuery,此代码也能很好地工作选择2

I saw this code in Select2 -
Clearing Selections

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

This code works well with jQuery even without Select2

稚气少女 2024-07-12 00:36:55

你可以简单地通过替换 html 来完成

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

You can do simply by replacing html

$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');
妞丶爷亲个 2024-07-12 00:36:55

这会将现有的 mySelect 替换为新的 mySelect。

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

This will replace your existing mySelect with a new mySelect.

$('#mySelect').replaceWith('<Select id="mySelect" size="9">
   <option value="whatever" selected="selected" >text</option>
   </Select>');
表情可笑 2024-07-12 00:36:55

使用 jquery prop() 清除所选选项

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

Uses the jquery prop() to clear the selected option

$('#mySelect option:selected').prop('selected', false);
久夏青 2024-07-12 00:36:55
  1. 首先清除所有现有选项,执行第一个(--Select--)

  2. 使用循环一附加新选项值一个

    $('#ddlCustomer').find('选项:not(:first)').remove(); 
      for (var i = 0; i < oResult.length; i++) { 
         $("#ddlCustomer").append(new Option(oResult[i].CustomerName, oResult[i].CustomerID + '/' + oResult[i].ID)); 
      } 
      
  1. First clear all exisiting option execpt the first one(--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));
    }
    
ヅ她的身影、若隐若现 2024-07-12 00:36:55

另一种方式:

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

在此链接下,有一些很好的做法 https://api.jquery.com/select/

Another way:

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

Under this link, there are good practices https://api.jquery.com/select/

不忘初心 2024-07-12 00:36:55
$("#id option").remove();
$("#id").append('<option value="testValue" >TestText</option>');

第一行代码将删除选择框的所有选项,因为没有提到选项查找条件。

第二行代码将添加具有指定值(“testValue”)和文本(“TestText”)的选项。

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

恰似旧人归 2024-07-12 00:36:55

基于 mauretto 的答案,这更容易阅读和理解:

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

要删除除具有特定值的选项之外的所有选项,您可以使用以下命令:

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

如果要添加的选项已经存在,这会更好。

Building on mauretto's answer, this is a little easier to read and understand:

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

飘逸的'云 2024-07-12 00:36:55

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

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>
');
埋情葬爱 2024-07-12 00:36:55

我在网上发现了类似下面的内容。 像我的情况一样,有数千个选项,这比 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;
}

更多信息此处

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.

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.

掐死时间 2024-07-12 00:36:55
$("#control").html("<option selected=\"selected\">The Option...</option>");
$("#control").html("<option selected=\"selected\">The Option...</option>");
望喜 2024-07-12 00:36:55

感谢我收到的答案,我能够创建如下所示的内容,以满足我的需求。 我的问题有点含糊。 感谢您的关注。 我的最后一个问题是通过在我想要选择的选项中包含“选定”来解决的。

$(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>

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>

分开我的手 2024-07-12 00:36:55

只需一行即可从选择标记中删除所有选项,然后在添加任何选项后,再创建第二行来添加选项。

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

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

还有一条捷径,但没有尝试

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

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'));
鸩远一方 2024-07-12 00:36:55
$('#mySelect')
    .empty()
    .append('<option value="whatever">text</option>')
    .find('option:first')
    .attr("selected","selected")
;
$('#mySelect')
    .empty()
    .append('<option value="whatever">text</option>')
    .find('option:first')
    .attr("selected","selected")
;
暮凉 2024-07-12 00:36:55

不确定“添加一个并选择它”到底是什么意思,因为无论如何它都会被默认选择。 但是,如果您要添加多个,那就更有意义了。 怎么样:

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

对“编辑”的响应:您能否澄清“此选择框由一组单选按钮填充”的含义? 元素。

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.

り繁华旳梦境 2024-07-12 00:36:55

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

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

If your goal is to remove all the options from the select except the first one (typically the 'Please pick an item' option) you could use:

$('#mySelect').find('option:not(:first)').remove();
掩饰不了的爱 2024-07-12 00:36:55

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

修复方法是使用标准 DOM 方法/属性(如海报原文所示)来清除而不是 jQuery - 仍然使用 jQuery 来添加选项。

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

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;
幸福%小乖 2024-07-12 00:36:55

为什么不直接使用普通的 javascript 呢?

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

why not just use plain javascript?

document.getElementById("selectID").options.length = 0;
鹤舞 2024-07-12 00:36:55
$('#mySelect')
    .empty()
    .append('<option selected="selected" value="whatever">text</option>')
;
$('#mySelect')
    .empty()
    .append('<option selected="selected" value="whatever">text</option>')
;
请叫√我孤独 2024-07-12 00:36:55
$('#mySelect')
    .find('option')
    .remove()
    .end()
    .append('<option value="whatever">text</option>')
    .val('whatever')
;
$('#mySelect')
    .find('option')
    .remove()
    .end()
    .append('<option value="whatever">text</option>')
    .val('whatever')
;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文