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

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

How do you remove all the options of a select box and then add one option and select it with jQuery?

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

我的选择框如下。

1
<Select id="mySelect" size="9" </Select>

编辑:以下代码有助于链接。但是,(在Internet Explorer中).val('whatever')没有选择添加的选项。(我在.append.val中使用了相同的"值"。)

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

编辑:试图让它模仿这段代码,每当页面/表单被重置时,我都使用下面的代码。此选择框由一组单选按钮填充。.focus()更接近,但似乎选择的选项不像选择.selected="true"那样。我现有的代码没有任何问题-我只是在尝试学习jquery。

1
2
3
4
var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)","Foo");
mySelect.options[0].selected="true";

编辑:所选答案与我需要的答案很接近。这对我很有用:

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

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


1
2
3
4
5
6
7
$('#mySelect')
    .find('option')
    .remove()
    .end()
    .append('<option value="whatever">text</option>')
    .val('whatever')
;

1
2
3
4
$('#mySelect')
    .empty()
    .append('<option selected="selected" value="whatever">text</option>')
;

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

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

我在IE7中有一个bug(在IE6中工作正常),使用上面的jquery方法可以清除DOM中的select,但不会在屏幕上清除。使用IE开发人员工具栏,我可以确认选择已被清除并有新的项目,但是选择仍然显示旧项目-即使您不能选择它们。

修复方法是使用标准的dom方法/属性(就像最初的海报一样)来清除,而不是使用jquery-仍然使用jquery来添加选项。

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


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

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

不确定"添加一个并选择它"是什么意思,因为默认情况下会选择它。但是,如果您要添加多个,这将更有意义。比如:

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

回答"编辑":你能解释一下你所说的"这个选择框由一组单选按钮填充"是什么意思吗?元素。


1
2
3
4
5
6
$('#mySelect')
    .empty()
    .append('<option value="whatever">text</option>')
    .find('option:first')
    .attr("selected","selected")
;

1
$("#control").html("<option selected="selected">The Option...</option>");

多亏了我收到的答案,我能够创造出像下面这样的东西,以满足我的需要。我的问题有点模棱两可。感谢您的跟进。我的最后一个问题是通过在我想要选择的选项中包含"已选择"来解决的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$(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
1
2
3
4
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
<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--)

  • 使用循环逐个附加新选项值

    1
    2
    3
    4
    $('#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改成新数据怎么样?

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

    另一个例子:

    1
    2
    3
    4
    5
    $('#mySelect').html('
        <option value="1" selected>text1</option>
        <option value="2">text2</option>
        <option value="3" disabled>text3</option>
    '
    );

    另一种方式:

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

    在此链接下,有一些良好的实践https://api.jquery.com/select/


    我在网上发现了如下的东西。在我的情况下,有成千上万的选择,这比jquery中的.empty().find().remove()快得多。

    1
    2
    3
    4
    5
    6
    7
    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;
    }

    更多信息在这里。


    基于莫雷托的回答,这有点容易理解和理解:

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

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

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

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


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

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

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


    这将用新的myselect替换现有的myselect。

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

    只需替换HTML即可

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

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

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

    我在select2中看到了这个代码https://select2.org/programmatic control/add select clear items清除选择

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


    希望它能起作用

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

    • 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

    1
    2
    3
    4
    5
    6
    7
    var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'};

    $('#selectID').empty();

    $.each(listToAppend, function(val, text) {
        $('#selectID').append( new Option(text,val) );
      });
    1
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">


    [cc lang="javascript"]var select = $('#mySelect');
    select.find('option').remove().end()
    .append($('

    推荐阅读

      linux命令添加文件?

      linux命令添加文件?,工作,简介,数据,系统,文件,命令,操作,文件名,内容,终端,l

      linux添加自启命令?

      linux添加自启命令?,服务,状态,密码,系统,脚本,第三,人员,标准,在线,实时,Pyt

      linux没有命令行选项?

      linux没有命令行选项?,系统,首页,命令,工具,分析,第一,软件,异常,终端,空格,

      linux快速删除命令行?

      linux快速删除命令行?,系统,软件,名称,数据,命令,文件,档案,不了,电脑,通用,l

      linux自启命令添加?

      linux自启命令添加?,服务,系统,工具,第三,第一,代码,密码,标准,项目,实时,lin

      删除linux文件命令?

      删除linux文件命令?,名称,不了,文件夹,命令,文件,目录,方法,指令,子目录,选

      linux下删除用户命令?

      linux下删除用户命令?,系统,代码,邮箱,用户组,命令,用户,名称,管理,电脑,账

      linux的删除所有命令?

      linux的删除所有命令?,不了,系统,名称,命令,文件夹,文件,目录,档案,数据,环

      linux删除类型命令?

      linux删除类型命令?,系统,档案,命令,文件,名称,环境,数据,不了,目录,文件夹,

      linux命令删除文件夹?

      linux命令删除文件夹?,系统,名称,环境,文件夹,不了,命令,文件,数据,档案,目

      linux命令怎么添加组?

      linux命令怎么添加组?,系统,密码,管理,用户,电脑,代码,新增,用户组,命令,账

      linux删除用什么命令?

      linux删除用什么命令?,档案,系统,命令,文件夹,文件,不了,名称,目录,终端,指

      linux删除用户组命令?

      linux删除用户组命令?,管理,系统,密码,电脑,名称,用户,用户组,名字,信息,工

      linux添加账户的命令?

      linux添加账户的命令?,密码,系统,信息,用户,软件,地址,状态,数字,命令,用户

      linux系统添加命令?

      linux系统添加命令?,系统,密码,工作,简介,术语,地址,命令,文件,目录,用户,Lin

      linux删除整行的命令?

      linux删除整行的命令?,系统,标的,数字,连续,档案,命令,光标,文件,模式,编辑,

      linux添加一条命令?

      linux添加一条命令?,项目,数据,工具,材料,电脑,系统,密码,软件,环境,管理,假

      添加字符串命令linux?

      添加字符串命令linux?,情况,名称,文件,位置,名字,地方,连续,信息,命令,内容,L

      linux命令行怎么删除?

      linux命令行怎么删除?,系统,不了,名称,文件夹,命令,文件,档案,目录,指令,子

      删除缓存的linux命令?

      删除缓存的linux命令?,地址,系统,网络,信息,电脑,情况,服务,缓存,软件,分析,l