Skip to content

Instantly share code, notes, and snippets.

@HugoPresents
Last active December 22, 2015 03:28
Show Gist options
  • Save HugoPresents/6410195 to your computer and use it in GitHub Desktop.
Save HugoPresents/6410195 to your computer and use it in GitHub Desktop.
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