<option> tag, display:none and jquery
I have a div
that is being used as a dialog with jQuery's .dialog()
. This div has a select box with options. The options the user has already selected are displayed on the main page. They can remove options from the main page and can open the dialog multiple times to add more options.
I populate the select box with all possible options on page load, but then when I open the dialog box I use jQuery's hide()
to hide the options that the user has already selected and are displayed on the main page. This adds the CSS display:none;
to the element in question, which IE ignores on <option>
tags and displays anyway.
I can easily enough call remove()
instead and remove it from the DOM. However, if the user selects some options, them removes them on the main page, then opens the dialog again to select more options, the options are no longer in alphabetical order, the options that were removed from the DOM and put back in it are now at the bottom since I开发者_如何学编程 used .append()
.
Is there any way to get IE to hide <option>
tags? Or is there a better way to do this? Or is there a way to insert in alphabetical order simply?
If you need to remove it from the DOM, you could store the options in an array. One array (or object) for each option list. Then removing options from the list itself is reversable. You can always rebuild the select menu again from the array. Just populate the array once the dom-ready event fires.
Demo online: http://jsbin.com/avuru
$(function(){
// Define variables to be used throughout this code
var colors = [];
var list = $("select[name='colors']");
var btnRestore = $("button[name='restore']");
var btnRemove = $("button[name='remove']");
// Cycle through each option, adding its value and text to our collection
$("option", list).each(function(i, o){
colors.push({ 'key':$(this).val(),'val':$(this).text() });
});
// Remove any remaining options, and add collection back into dropdownlist
$(btnRestore).click(function(){
$("option", list).remove();
for (var i = 0; i < colors.length; i++) {
$("<option>").val(colors[i].key).text(colors[i].val).appendTo(list);
}
});
// Remove first option from list - used to test 'Restore' functionality
$(btnRemove).click(function(){
$("option:first", list).remove();
});
});
I would clone the list of options before modifying it and keep the original around. That way you can reinsert it clean by replacing the modified one with the orignal.
精彩评论