Last active
December 22, 2015 03:28
-
-
Save HugoPresents/6410195 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery.fn.filterByText = function(textbox, selectSingleMatch) { | |
return this.each(function() { | |
var select = this; | |
var options = []; | |
$(select).find('option').each(function() { | |
options.push({value: $(this).val(), text: $(this).text(), disabled:$(this).is(':disabled')}); | |
}); | |
$(select).data('options', options); | |
$(textbox).bind('change keyup', function() { | |
var options = $(select).empty().scrollTop(0).data('options'); | |
var search = $.trim($(this).val()); | |
var regex = new RegExp(search,'gi'); | |
$.each(options, function(i) { | |
var option = options[i]; | |
if(option.text.match(regex) !== null) { | |
var newOption = $('<option>'); | |
if(option.disabled) { | |
newOption.attr('disabled', 'disabled'); | |
} | |
newOption.text(option.text).val(option.value); | |
$(select).append(newOption); | |
} | |
}); | |
if (selectSingleMatch === true && | |
$(select).children().length === 1) { | |
$(select).children().get(0).selected = true; | |
} | |
}); | |
}); | |
}; | |
// example | |
$(function() { | |
$('.category-filter-select').filterByText($('.category-filter'), true); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment