javascript 使用 jQuery 删除值后刷新/重新加载下拉列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26162128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:36:09  来源:igfitidea点击:

Refresh/reload a dropdown list after removing values with jQuery?

javascriptjqueryhtmldrop-down-menucascade

提问by DreamTeK

The following code removes dropdown list values based on text entered in a textbox.

以下代码根据在文本框中输入的文本删除下拉列表值。

FIDDLE DEMO

小提琴演示

JQUERY

查询

var ddl = ('#ddl'),
  txt = ('#txt');

$(txt).change(function() {   
  var x = $(txt).val(),
    li = $(ddl).html();

  if (x.length != 0) {
    $(ddl).html(li);
    $(ddl + ' :not([value="' + x + '"])').remove();
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txt" type="text" placeholder="Enter a number...">

<select id="ddl">
  <option value="0" selected="selected">Select...</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

QUESTION

问题

How to restore dropdownlist values back to initial state when a new value is entered into the textbox?

在文本框中输入新值时,如何将下拉列表值恢复到初始状态?

I have been attempting to use:

我一直在尝试使用:

$(ddl).selectmenu("refresh"); 

but this stops the script from working as expected.

但这会阻止脚本按预期工作。

回答by leopik

Like so

像这样

    ...
    $(ddl).html(li);
    $(ddl + ' :not([value="' + x + '"])').hide();
} else {
    $(ddl + ' :not([value="' + x + '"])').show();
}
...

Instead of removing the item completely, you simply hide. When you empty the input field, re-show all the items.

您只需隐藏即可,而不是完全删除该项目。当您清空输入字段时,重新显示所有项目。

回答by Pedro Ferreira

You could try something like this:

你可以尝试这样的事情:

var ddl = ('#ddl'),
    txt = ('#txt');

$(txt).change(function () {
    var x  = $(txt).val(),
        li = $(ddl).html();

    $(ddl + ' option').show();

    if (x.length != 0) {     
        $(ddl).html(li);
        $(ddl + ' option:not([value="' + x + '"])').hide();
        $(ddl + ' option[value="' + x + '"]').prop('selected',true);
    }
});