Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Thanks

like image 370
SoLoGHoST Avatar asked Jun 12 '10 04:06

SoLoGHoST


People also ask

How do I select more than one option in drop down?

Selecting multiple options vary in different operating systems and browsers: For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.

Is used to select multiple option?

To select multiple options, hold down the Control (Ctrl) key if you are using a PC system or the Apple key if you are using a Macintosh system, while you click on the several options that you wish to select.

What does select multiple mean?

(computing, graphical user interface) Multiple selection; the ability to have more than one item selected at the same time.


2 Answers

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);
    }
}
like image 123
Mark Byers Avatar answered Sep 28 '22 11:09

Mark Byers


You can do it much easier using jQuery:

$('#actions_list option:selected').remove()
like image 27
dzida Avatar answered Sep 28 '22 11:09

dzida