Forked from dave1010/jquery.detach-select-options.js
Created
October 3, 2012 08:25
-
-
Save SilverPreece/3825794 to your computer and use it in GitHub Desktop.
jQuery plugin to detach (hide) select options and add them again.
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
// 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