Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deselect all options in Multiple Select with 1 option

I currently have the following js code

function clearMulti(option)
{
    var i;
    var select = document.getElementById(option.parentNode.id);
    for(i=1;i<select.options.length;i++)
         {
        select.options[i].selected=false;
    }
}

and

function clearAllOpt(select)
{
    select.options[0].selected = false;
}

The first one deselects all options in the multiple select when called and the second clears the first option whenever anything else is selected.

The need for this is that the first option is for All.

This all works fine and dandy in FF, but in IE8 nothing happens... any suggestions on how to get this to work in both?

This is called from a jsp page... code below -- edits were made for how ids and things are populated since it's database info and other things that I probably shouldn't give out :) but this should give you the info that you're looking for.

<select id="blahSelect" name="blahSelect" style="width:80%" size=7 multiple>
     <option id="All Blah" onclick="clearMulti(this)">All Blah</option>
     <option id="**from sql**" onclick="clearAllOpt(this.parentNode)">**from sql**</option>
</select>

Thanks in advance.

like image 334
Shaded Avatar asked Dec 22 '22 04:12

Shaded


2 Answers

May this easily

select.selectedIndex = -1;

Note: The value "-1" will deselect all options (if any).

Source: http://www.w3schools.com/jsref/prop_select_selectedindex.asp

like image 186
Dmitry Avatar answered Feb 03 '23 21:02

Dmitry


IE8 does not fire onclick events on option elements.

Also note that selectedIndex returns the first selected option, and does not change according to the last selected option. This leads to issues when ALL is checked, and you try to check other options with CTRL held down.

You could try something like this:

<script type="text/javascript">
function excludeFirstOption(select) {

    if (select.selectedIndex === 0) {
        for (var i=0; i<select.options.length; i++) {
            select.options[i].selected = false;
        }
    }
}
</script>

<select size="7" multiple="multiple" onchange="excludeFirstOption(this)">
     <option>All</option>
     <option>Item 1</option>
     <option>Item 2</option>
     <option>Item 3</option>
     <option>Item 4</option>
</select>
like image 28
Thomas Kjørnes Avatar answered Feb 03 '23 19:02

Thomas Kjørnes