Search Qodo.co.uk

Javascript: Select all options for a select box

Here’s a javascript function that will allow the user to select all or none of the options in a multiple select box. It is quite simple to use, first either provide the id of the select box or the actual select box object and it will do the rest.

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

The above example will select all options for the select box with the id ’selectbox1′.

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

And that 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).

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;
		}
	}
}

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!

Download the example JavaScript: Select all options in a select box now!

Post Details

Blog Archives

Blog Categories

Comments

3 Responses to “Javascript: Select all options for a select box”

  • Posted by br41nless
  • Permalink

thank you stewart


  • Posted by miles
  • Permalink

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


[...] the user to select all or none of the options in a multiple select box. It is quite simple to …http://www.qodo.co.uk/blog/javascript-select-all-options-for-a-select-box[...]


Leave Feedback

Your comments