首页 文章

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

提问于
浏览
921

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

我的选择框如下 .

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

编辑:以下代码有助于链接 . 但是,(在Internet Explorer中) .val('whatever') 未选择已添加的选项 . (我确实在 .append.val 中都使用了相同的'value' . )

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

但这两个答案都让我得到了最后的解决方案..

21 回答

  • 73
    $("#control").html("<option selected=\"selected\">The Option...</option>");
    
  • 1535
    $("#id option").remove();
    $("#id").append('<option value="testValue" >TestText</option>');
    

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

    第二行代码将添加具有指定值(“testValue”)和Text(“TestText”)的Option .

  • 635

    你可以简单地替换html

    $('#mySelect')
    .html('<option value="whatever" selected>text</option>')
    .trigger('change');
    
  • -1
    $('#mySelect')
        .empty()
        .append('<option value="whatever">text</option>')
        .find('option:first')
        .attr("selected","selected")
    ;
    
  • 23

    感谢我收到的答案,我能够创建符合我需求的以下内容 . 我的问题有些含糊不清 . 感谢您的跟进 . 通过在我想要选择的选项中包含“已选择”来解决我的最终问题 .

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

    我在网上发现了类似下面的内容 . 有了成千上万的选项,比如我的情况,这比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;
    }
    

    更多信息here .

  • 6

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

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

    这将使用新的mySelect替换现有的mySelect .

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

    我在IE7中有一个错误(在IE6中工作正常),使用上面的jQuery方法将清除DOM中的选择而不是屏幕上的选择 . 使用IE Developer Toolbar我可以确认选择已被清除并有新项目,但在视觉上选择仍显示旧项目 - 即使您无法选择它们 .

    解决方法是使用标准的DOM方法/特性(如海报原版)清除而不是jQuery - 仍然使用jQuery添加选项 .

    $('#mySelect')[0].options.length = 0;
    
  • 7
    • 首先清除所有现有选项execpt第一个( - 选择 - )

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

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

    其他方式:

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

    在这个链接下,有良好做法https://api.jquery.com/select/

  • 4
    $('#mySelect')
        .empty()
        .append('<option selected="selected" value="whatever">text</option>')
    ;
    
  • 112
    • 保存要附加在对象中的选项值

    • 清除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>
    
  • 3
    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('');
    
  • 10

    在mauretto的回答基础上,这更容易阅读和理解:

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

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

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

    如果要添加的选项已经存在,那将会更好 .

  • 6

    如何将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>
    ');
    
  • 1

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

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

    不确定“添加一个并选择它”的确切含义,因为无论如何都会默认选择它 . 但是,如果你要添加多个,那就更有意义了 . 怎么样的:

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

    Response to "EDIT" :你能澄清"This select box is populated by a set of radio buttons"的意思吗? <select>元素不能(合法地)包含<input type = "radio">元素 .

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

    为什么不只是使用普通的JavaScript?

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

    希望它会奏效

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

相关问题