Jump to: navigation or main content.

Selecting all select options

This example will select all options for the select box with the id 'selectbox1':-

<input type="button" name="Button" value="All" onclick="selectAll('selectbox1',true)" />

And this example will select none of the options for the select box by passing the select object and saying we don't want them all selected (false):-

 <input type="button" name="Button" value="All" onclick="selectAll(document.getElementById('selectbox2'),false)" />

The function

Just pass the ID of the element or and whether you want all of the options selected or not and it'll do the rest!

function selectAll(selectBox,selectAll) { 
// have we been passed an ID
if (typeof selectBox == "string") {
selectBox = document.getElementById(selectBox);
}
// is the select box a multiple select box?
if (selectBox.type == "select-multiple") {
for (var i = 0; i < selectBox.options.length; i++) {
selectBox.options[i].selected = selectAll;
}
}
}

Of course, If your select box is not a multiple select, it will do nothing! If this has been of some help to you, let me know!


Archives

Categories

Comments (8)

What others have said about this blog post.

  1. 27 Aug 2007 br41nless said:

    thank you stewart

  2. 19 Feb 2008 miles said:

    MANY thanks this helped me immediately with a problem I was having!

  3. 09 Oct 2008 Worrawat Sakulwong said:

    thank you

  4. 13 Jul 2009 Synbios said:

    thanks mate, you saved me a lot of researching in javascript :D

  5. 01 Sep 2009 Bill Bartmann said:

    I'm so glad I found this site...Keep up the good work

  6. 02 Sep 2009 Bill Bartmann said:

    This site rocks!

  7. 24 May 2010 mahen said:

    That really helped. Thank you very much

  8. 05 Jun 2010 Knight Samar said:

    Thanks! That was neat :)


This thread has been closed from taking new comments.