Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

automatically select all options in a multiple select box

Status
Not open for further replies.

PushCode

Programmer
Dec 17, 2003
573
US
I'm wondering how I can automatically select all options in a multiple select box when the page loads. That is, not actually submit the form or anything, just highlight all options in the list.

Is there some Javascript I can run onLoad that will take care of this.

<select multiple name=&quot;selectNames&quot; size=&quot;10&quot;>
<option value=&quot;#dynamic.value#&quot;>#dynamic.value#</option>
</select>

 
PushCode,

This should do the trick for you:

Code:
<HTML>
<HEAD>

<SCRIPT LANGUAGE=&quot;JavaScript&quot;>
<!--

    function selectAll()
    {
        selectObj = document.forms['myForm'].mySelect;
		for (var _loop=0; _loop<selectObj.length; _loop++) selectObj.options[_loop].selected = true;
    }

//-->
</SCRIPT>

</HEAD>
<BODY onLoad=&quot;selectAll();&quot;>

<FORM NAME=&quot;myForm&quot;>
    <SELECT NAME=&quot;mySelect&quot; MULTIPLE>
		<OPTION VALUE=&quot;1&quot;>Option 1</OPTION>
		<OPTION VALUE=&quot;2&quot;>Option 2</OPTION>
		<OPTION VALUE=&quot;3&quot;>Option 3</OPTION>
		<OPTION VALUE=&quot;4&quot;>Option 4</OPTION>
	</SELECT>
</FORM>

</BODY>
</HTML>

Hope this helps!

Dan
 
I can think of two ways to do it:

1: by setting the default value
<select multiple name=&quot;selectNames&quot; size=&quot;10&quot;>
<option selected value=&quot;#dynamic.value#&quot;>#dynamic.value#</option>
</select>

2: by javascript:
Code:
<script language =&quot;javascript&quot;>
function selectAll(selectField) {
   for (var i=0; i<selectField.options.length; i++) {
      selectField.options[i].selected = true;
   }
}

// to initialize all options
selectAll(document.forms[0].selectNames);
</script>
 
Just adding selected attribute to each option element will do:
Code:
<select multiple name=&quot;selectNames&quot; size=&quot;10&quot;>
  <option value=&quot;#dynamic.value#&quot; selected>Option 1</option>
  <option value=&quot;#dynamic.value#&quot; selected>Option 2</option>
  <option value=&quot;#dynamic.value#&quot; selected>Option 3</option>
</select>
 
Thanks for the quick responses everyone.

Question: If I use the 'selected' attribute of the select box and a user decides they want to select their own options, not all, when they submit the form, will only the options the user wants be submited, or will they all since the 'selected' attribut is coded into the select box?
 
Great!

Classic case of over thinking it on my part ;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top