0

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.

1
  • This is redundant: var li = $(ddl).html(); $(ddl).html(li); Commented Oct 2, 2014 at 13:43

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I've been working on this all day! Thank you!!!!!!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.