Skip to content

Instantly share code, notes, and snippets.

@ianthrive
Last active August 29, 2015 14:02
Show Gist options
  • Save ianthrive/c318b0ed7006e2646f26 to your computer and use it in GitHub Desktop.
Save ianthrive/c318b0ed7006e2646f26 to your computer and use it in GitHub Desktop.
Filter a <select> list with a <input type="text">.
// depends on jquery
function filterSelectWithField(selectList, searchField) {
selectList = $(selectList);
searchField = $(searchField);
options = selectList.find('option').clone();
timer = null;
function sanitize(str) {
return $.trim(str).replace(/\s+/g, ' ').toLowerCase();
}
searchField.on('keyup', function(e) {
var searchTerm = sanitize($(this).val());
clearTimeout(timer);
timer = setTimeout(function() {
if(!searchTerm) {
selectList.empty().append(options.clone());
return;
}
matches = options.filter(function(idx) {
return sanitize($(this).text()).indexOf(searchTerm) != -1;
}).clone();
selectList.empty().append(matches);
}, 500);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment