faqts : Computers : Programming : Languages : JavaScript : Forms : SELECT

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

36 of 41 people (88%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I pre set a value of a <select>

Sep 28th, 2000 04:05
Rey Nuņez, Paul Culmsee,


You can use the SELECTED attribute of the OPTION element to indicate 
which option is the default choice.

HTML syntax is:
   <OPTION SELECTED ... > 
and to set in script
   select.options[iIndex].selected  

This property returns or accepts only a boolean value, meaning true if 
set, and false if not. The property is read/write with a default value 
of false.

If none of the options in a SELECT has the property set, the first item 
is selected by default.

The SELECTED property is also used to determine which value(s) are 
submitted with the form. The following example shows how the SELECTED 
property is used to retrieve the chosen options in a SELECT object 
whose MULTIPLE attribute is set to allow choosing multiple items in a 
list. 

<script language="JavaScript">
<!--
function getSels(){
var list=document.forms['theForm'].elements['theSelect'];
var sels="";
for (i=0;i<list.options.length;i++)
  if (list.options[i].selected)
    sels += list.options[i].text+"\n";
if (sels.length>0) alert("You have selected: \n"+sels);
else alert("You have not selected anything.");
}
//-->
</script>

<div align="center">
<form name="theForm">
<table cellpadding=5>
<tr>
  <td><select name="theSelect" multiple size=5>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
<option>Item 4</option>
<option>Item 5</option></select></td>
  <td><input type="button" onclick="getSels()" value="Get 
Selected"></td></tr>
</table></form>