title: Jquery Listbox / Textbox filter
body: <p>I have the following jquery function for filtering the contents of a listbox on the onkeyup event from a textbox. </p>
  
  <pre><code>function DoListBoxFilter(listBoxSelector, filter, keys, values) {
      var list = $(listBoxSelector);
      var selectBase = '&lt;option value="{0}"&gt;{1}&lt;/option&gt;';
  
      list.empty();
      for (i = 0; i &lt; values.length; ++i) { //add elements from cache if they match filter
  
          var value = values[i];
  
          if (value == "" || value.toLowerCase().indexOf(filter.toLowerCase()) &gt;= 0) {
              var temp = String.format(selectBase, keys[i], value);
              list.append(temp);
          }
      }
  }
  </code></pre>
  
  <p>It works great for small to medium size lists, but it is a little bit slow when working with lists over 300-400 items... Can anyone help with some ideas to optimize the javascript a little bit to speed up the function?</p>
  
  <p>The function is invoked with the following code:</p>
  
  <pre><code>    $('#&lt;% = txtSearch.ClientID %&gt;').keyup(function() {
  
          var filter = $(this).val();
  
          DoListBoxFilter('#&lt;% = lstPars.ClientID %&gt;', filter, keys_&lt;% = this.ClientID %&gt;, values_&lt;% = this.ClientID %&gt;);
      });
  </code></pre>
  
  <p>To use this, I bind an asp.net listbox and also populate two javascript arrays (key and value) on the page.</p>
  
  <p>This IS storing the data in two places on the page, but using this method I am able to use the postback of the listbox to get the selected value without using javacript to extract the value and cache it in a hidden div. (it also saves having to run the function at page load on the clients browser.. and that is really the function where I am seeing the slowness, so storing in two places speeds up the page rendering)</p>
  
  <p>I found that I needed to use the javascript array approach because most browsers don't acknowledge any attempts to hide an option tag... only Firefox appears to do it.</p>
  
  <p>I'm not sure its possible to optimize and speed this code up any more, but if anyone has any ideas I would appreciate it.</p>
  
  <p>Thanks,
  Max Schilling</p>