Skip to content

Instantly share code, notes, and snippets.

@mqudsi
Last active November 6, 2015 23:48
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 mqudsi/6cec1827ef931eed69d0 to your computer and use it in GitHub Desktop.
Save mqudsi/6cec1827ef931eed69d0 to your computer and use it in GitHub Desktop.
$(document).ready(function () {
$("select.magic").each(function () {
var select = $(this);
if (!select.hasOwnProperty("removedExtraneous")) {
select.removedExtraneous = [];
}
var filterFunction = function () {
var oldVal = select.val();
select.children("option.extraneous").each(function () {
//save to return it later
select.removedExtraneous.push($(this));
$(this).detach();
});
//select the matching "proper" option
select.val(oldVal);
};
select.bind("keydown", function (event) {
if (event.keyCode == 32) {
filterFunction();
}
});
select.bind("mousedown", filterFunction);
select.bind("blur", function () {
//select the "proper" equivalent
var oldVal = select.val();
select.children("option")
.not(".extraneous")
.filter(function () {
return this.value == oldVal
}).prop("selected", "true");
//return the removed elements so it works on tab back
if (select.append) {
var option;
while (option = select.removedExtraneous.pop()) {
select.append(option);
}
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment