Problem with multiple select removing more than 1 option
There seems to be a problem with the JS Code for Opera browsers, as it only removes the last option tag that is selected within a multiple select tag, can someone please help me.
Here is the HTML for this:
<select id="actions_list" name="layouts" multiple style="height: 128px; width: 300px;">
<option value="forum">forum</option>
<option value="collapse">collapse</option>
<option value="[topic]">[topic]</option>
<option value="[board]">[board]</option>
<开发者_运维问答/select>
Of course it's within a form tag, but there's a ton more code involved with this form, but here is the relevant info for this.
Here is the JS that should handle this, but only removes the last selected option in Opera, not sure about other browsers, but it really needs to remove all selected options, not just the last selected option...
var action_list = document.getElementById("actions_list");
var i = action_list.options.length;
while(i--)
{
if (action_list.options[i].selected)
{
action_list.remove(i);
}
}
What is wrong with this? I can't figure it out one bit.
It's easiest to do this with jQuery but it you want to do this using plain Javascript you can.
The problem you are experiencing is that when you remove an item from the options list in Opera it deselects all the selected items, so only the first is removed. A workaround is to first remember which items were selected before removing any.
var action_list = document.getElementById("actions_list");
// Remember selected items.
var is_selected = [];
for (var i = 0; i < action_list.options.length; ++i)
{
is_selected[i] = action_list.options[i].selected;
}
// Remove selected items.
i = action_list.options.length;
while (i--)
{
if (is_selected[i])
{
action_list.remove(i);
}
}
You can do it much easier using jQuery:
$('#actions_list option:selected').remove()
$.each($('[name="alltags"] option:selected'), function( index, value ) {
$(this).remove();
});
try this instead to remove multiple selection
Removing multiple options from select based on condition:
while(SelectBox.length > 1){
if(SelectBox[SelectBox.length -1].text != "YourCondition"){
SelectBox.remove(SelectBox.length -1);
}
}
精彩评论