Last active
August 29, 2015 14:02
-
-
Save ianthrive/c318b0ed7006e2646f26 to your computer and use it in GitHub Desktop.
Filter a <select> list with a <input type="text">.
This file contains 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
// 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