Depends what you want the list to finally contain (as opposed to being
visible, that is).
Here's an alternative...

$(document).ready(function() {
  var arr = ['C+
+','D','HTML','CSS','C#','PHP','Python','XML','JavaScript','Photoshop']
    , alc = []
    , list = $('#list');
  $.each(arr, function(i,v){
      list.append('<li>'+v+'</li>');
      alc[i] = v.toLowerCase();
    });
  list = $('li', list);
  $('#filter').keyup(function(){
      var v = this.value ? this.value.toLowerCase() : 0;
      list.each(function(i){
          $(this)[v && alc[i].indexOf(v) == -1 ? 'hide' : 'show']();
        });
    });
});

This doesn't change the list contents, simply hides those elements not
relevant to the value of the filter input box. It also stores the
lowercase options up front, and stores the object of all the list
elements so that the keyup handler doesn't have to go find them each
time it runs.

Mark wrote:
> Hi... so I'm new to jQuery.  I'm using it to dynamically filter a
> list... I'm wondering if this is the best/most efficient method to go
> about doing it:
>
> <html>
> <head>
>         <title>jquery test</title>
>         <script type="text/javascript" src="js/jquery-1.2.3.min.js"></
> script>
>         <script type="text/javascript">
>         $(document).ready(function() {
>                 var arr = ['C+
> +','D','HTML','CSS','C#','PHP','Python','XML','JavaScript','Photoshop'];
>                 for(i=0; i<arr.length; ++i) {
>                         $('#list').append('<li>'+arr[i]+'</li>');
>                 }
>                 $('[EMAIL PROTECTED]').keyup(function() {
>                         $('#list').empty();
>                         for(i=0; i<arr.length; ++i) {
>                                 if($
> ('[EMAIL PROTECTED]').attr('value')==undefined||
> arr[i].toLowerCase().indexOf($
> ('[EMAIL PROTECTED]').attr('value').toLowerCase())!=-1)
>                                 {
>                                         $('#list').append('<li>'+arr[i]
> +'</li>');
>                                 }
>                         }
>                 });
>         });
>         </script>
> </head>
> <body>
>
> <ul id="list"></ul>
> <input name='filter' id="filter"/>
>
> </body>
> </html>
>
> See it in action: http://mechaflora.com/programming/filter
>
> Any suggestions on how I can do this better would be appreciated :) Or
> feel free to use the code for your own purposes if you think it's good.

Reply via email to