Changes

Jump to: navigation, search

Building Forms with JavaScript

2,115 bytes added, 14:54, 17 May 2007
JavaScript Drop-down / Select Object
The optional ''multiple'' attribute may be added to the <select> tag to enable multiple selection of items from the list.
 
=== Obtaining the Current Selection from the JavaScript Select Object ===
 
The Select object ocntains a number of properties that can be used to obtain the currently selected listy item:
 
'''name''' - The name of the Select Object instance
 
'''length''' - The number of items in the list
 
'''options''' - An array of options in the list. Each selectable option in the list has an entry in the array.
 
'''selectedIndex''' - the index of the currently selected item in the list.
 
The ''options'' array, in turn, has a '''length'' property that can be used to find the number of options contained in the array. Further, each element in the arrary contains the following properties:
 
'''index''' - the index into the array
 
'''defaultSelected''' - the state of the ''selected'' attribute
 
'''selected''' - specifies the current state of the option. Setting this to ''true'' selects this option
 
'''name''' - the value of the ''name'' attribute
 
'''text''' - the text that is displayed for this option
 
Using our car example fropm above we could output the value of the currently selected item by first finding the currently selectedIndex value, and then using this index to read the ''value'' of that element in the ''options'' array. The follow example demonstrates this:
 
<pre>
 
<html>
<head>
<title>JavaScript Select Example</title>
 
<script language="javascript" type="text/javascript">
function readSelection()
{
 
var index = document.myForm.carBrands.selectedIndex;
 
document.write("selectedIndex= " + index + "<br>");
 
var value = document.myForm.carBrands.options[index].value;
 
document.write("Selected Value = " + value + "<br>");
}
</script>
 
</head>
 
<body>
 
<form action="" name="myForm">
<select name="carBrands">
<option value="Ford" SELECTED>Ford Motor Company
<option value="GM">General Motors
<option value="Honda">Honda Motor Company
<ottion value="Toyota">Toyota Motor Company
<option value="Ford">Jaguar
<option value="Mazda">Mazda
<option value="Volvo">Volvo
</select>
<input type="BUTTON" value="Click to get Selection" onClick="readSelection()"/>
</form>
 
</body>
</html>
 
</pre>
== JavaScript Password Object ==

Navigation menu