Filtering select list via input box & jquery

I was wondering if I can help with filtering the select list using an input field via jquery.

This is how my js looks like but it doesn't seem to work. I am guessing this is because the options in the select list are not hidden.

    <script type="text/javascript">
    $(document).ready(function() {
        $("#inputFilter").change(function() {
            var filter = $(this).val();

            $("#selectList option").each(function() {
                var match = $(this).text().search(new RegExp(filter, "i"));
                if (match > 0) {
                    $(this).show(); // Does not work
                }
                else
                    $(this).hide();
            });
        });
    });
</script>

      

and here is my html

<input id="inputFilter" />
<select id="selectList">
    <option value="1111" >1111 - London</option>
    <option value="1112" >1112 - Paris </option>
</select>

      

+2


a source to share


3 answers


Please try the following:

$("#inputFilter").change(function() {
    var filter = $(this).val();
    //alert(filter);
    $("#selectList option").each(function() {
        var match = $(this).text().search(new RegExp(filter, "i"));
        //alert(match);
        if (match < 0 && $(this).text() != "--select--")  {                   
            $(this).attr("disabled",true);
        }
        else
            $(this).attr("disabled",false);

    });
});

      



You can see it in action here .

NTN

+4


a source


Try to disable rather than hide.

$(this).attr('disabled', 'disabled');

      



Another thing you could do is remove the variant from the DOM altogether.

0


a source


There is no attribute text

.

Try something like this:

<input id="inputFilter" />
<select id="selectList">
   <option value="1111">1111 - London</option>
   <option value="1112">1111 - Paris</option>
</select>

<script>
$(document).ready(function() {
   $("#inputFilter").change(function() {
      var filter = $(this).val();
      $("#selectList option").each(function() {
         var match = $(this).text().search(new RegExp(filter, 'i'));

         if (match > 0) {
            $(this).show();
         }
         else{
            $(this).hide();
         }
      });
   });
});
</script>

      

Edit: edited my answer because I misunderstood something.

0


a source







All Articles