admin管理员组

文章数量:1406340

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

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

Share Improve this question edited Oct 2, 2014 at 14:24 DreamTeK asked Oct 2, 2014 at 13:39 DreamTeKDreamTeK 34.4k29 gold badges124 silver badges178 bronze badges 1
  • This is redundant: var li = $(ddl).html(); $(ddl).html(li); – LcSalazar Commented Oct 2, 2014 at 13:43
Add a ment  | 

2 Answers 2

Reset to default 2

Like so

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

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

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);
    }
});

本文标签: javascriptRefreshreload a dropdown list after removing values with jQueryStack Overflow