Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SilverPreece/3825794 to your computer and use it in GitHub Desktop.
Save SilverPreece/3825794 to your computer and use it in GitHub Desktop.
jQuery plugin to detach (hide) select options and add them again.
// this is because of http://stackoverflow.com/questions/4398966/how-can-i-hide-select-options-with-javascript-cross-browser/4423543
// forked from dave1010's example to include removal of attached elements from the data() array
(function($){
$.fn.extend({detachOptions: function(o) {
var s = this;
return s.each(function(){
var d = s.data('selectOptions') || [];
s.find(o).each(function() {
d.push($(this).detach());
});
s.data('selectOptions', d);
});
}, attachOptions: function(o) {
var s = this;
return s.each(function(){
var d = s.data('selectOptions') || [];
// Walk backwards over the array here. splice() removes the element from the array,
// but this causes all array indices to be reduced by 1 in the result, which
// means a forward loop would miss the element immediately after the removed one.
for (var x = d.length - 1; x >= 0; x--) {
if (d[x].is(o)) {
s.prepend(d[x]); // Prepend rather than append because we're walking backwards
d.splice(x, 1);
s.data('selectOptions', d);
}
}
});
}});
})(jQuery);
// example
$('select').detachOptions('.removeme');
$('.b').attachOptions('[value=1]');');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment