Category

jQuery: search in dropdowns

Recently I was asked to implement search in long dropdowns. Our customer got stressed each time when he had had to find a product in the loooong list.
I tried to search for a solution in the Internet and there are at least two fancy ones. But one of them is very slow for long lists (well, we do need to search in long lists first of all) and the other one is simple but doesn't allow to select items manually.
So I ended up with very easy solution

(jQuery plugin should be included first):

<script type="text/javascript">
$(document).ready(function() {
$('#searchProduct').keyup(function() {
if ($('#searchProduct').val().length >= 3) { //search only after 3 chars are entered.
search = $('#searchProduct').val();
$('#selectProduct option').each(function(){
if ($(this).text().indexOf(search) > -1) {
$(this).attr('selected', 'yes');
}
});
}
});
});
</script>
<input type="text" size="20" id="searchProduct" value="" name="search">
<select id="selectProduct" name="whatever">
  <option value="1">-options here-</option>
  .....
</select>

And here's what I got:
search:

...but what if I have multiselect dropdown and want to select several items from search? Piece of cake :)

<script type="text/javascript">
$(document).ready(function() {
$('#searchProduct2').keyup(function() {
if ($('#searchProduct2').val().length >= 3) {
search = $('#searchProduct2').val();
$('#selectProduct2 option:selected').each(function(id){
$(this).removeAttr('selected');
});
$('#selectProduct2 option').each(function(){
if ($(this).text().indexOf(search) > -1) {
$(this).attr('selected', 'yes');
}
});
}
});
});
</script>

<input type="text" size="20" id="searchProduct2" value="" name="search">
<select id="selectProduct2" name="current_products[]" multiple="yes" size="10">
  <option value="1">-options here-</option>
  .....
</select>

search:

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <em> <strong> <cite> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.
© 2008-2009. Konstantin Artemov