views:

170

answers:

3

Hi all,

I was wondering if i could get some help with filtering a select list using an input box via jquery.

Here's what my js looks like, but it doesnt seem to work. I'm guessing this is because options within a select list are not hide-able.

    <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's my html

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

Try disabling instead of hiding.

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

Another thing you could do is delete the option from the DOM altogether.

BryanH
How would i go about deleting it from the dom.I'd probably also need to keep a clone of the original select list somewhere as well right?
zSysop
A: 

There's no text attribute.

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 misread somethings.

j.
+1  A: 

Please try this:

$("#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.

HTH

Raja