Created
April 17, 2012 01:41
-
-
Save bmc/2402822 to your computer and use it in GitHub Desktop.
Bind an <input> to a <select>, so the <input> will filter the <select> as the user types
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
# Ties a text <input> element and a <select> together, so that whatever | |
# is typed in the <input> filters the <select> list, dynamically. Assumes | |
# jQuery. | |
# | |
# DON'T modify the contents of the <select> list after binding the filter! | |
# | |
# Parameters | |
# | |
# inputSelector - jQuery selector string for the <input> | |
# selectSelector - jQuery selector string for the <select> | |
window.bindSelectFilter = (inputSelector, selectSelector) -> | |
input = $(inputSelector) | |
# Capture the original options and stash them in the jQuery select object. | |
select = $("#{selectSelector}") | |
options = $("#{selectSelector} option") | |
saved = [] | |
$.each(options, -> | |
saved.push([$(this).val(), $(this).text()]) | |
) | |
select.savedOptions = saved | |
input.keyup -> | |
filter = input.val()?.toLowerCase() | |
console.log filter | |
if filter? then $.trim(filter) else "" | |
# Update the select, based on what's in the filter. | |
new_html = "" | |
for opt in select.savedOptions | |
value = opt[0] | |
text = opt[1] | |
if (filter.length == 0) || (text.toLowerCase().indexOf(filter) == 0) | |
# Keep this one. | |
new_html += "<option value='#{value}'>#{text}</option>\n" | |
select.html(new_html) | |
# Sample usage: | |
window.bindSelectFilter("#my_filter_input", "#my_filtered_select") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment