Skip to content

Instantly share code, notes, and snippets.

@tmilewski
Created April 13, 2011 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmilewski/918590 to your computer and use it in GitHub Desktop.
Save tmilewski/918590 to your computer and use it in GitHub Desktop.
Filters a select field based a selection from another.
$(document).ready(function() {
$('.search select#search_tour_stop').filterBy('.search select#search_year');
}
jQuery.fn.filterBy = function(watch) {
options = new Array;
target = $(this);
target.find('option').each(function(index, option) {
if (index > 0) {
options.push( { filter: $(option).text().match(/\.(\d{2}) -/)[1], element: option } );
}
});
el = $(watch);
el.change(function () {
selected = $(watch +" option:selected");
value = selected.val().slice(2);
target.html('');
$.each(options, function(index, option) {
if (option.filter === value) {
target.append(option.element);
}
});
});
el.trigger('change');
};
$(document).ready(function() {
$('.search select#search_tour_stop').filterBy('.search select#search_year', 'data-filter');
}
jQuery.fn.filterBy = function(watch, attr) {
options = new Array;
target = $(this);
target.find('option').each(function(index, option) {
if (index > 0) {
options.push( { filter: $(option).attr('data-filter'), element: option } );
}
});
el = $(watch);
el.change(function () {
selected = $(watch +" option:selected");
value = selected.attr(attr);
target.html('');
$.each(options, function(index, option) {
if (option.filter === value) {
target.append(option.element);
}
});
});
el.trigger('change');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment