Categories:

JavaScript Kit > JavaScript Reference > Here

Elements Object

Last updated: March 30th, 2005

The elements object (array) allows you to access any element within a form generically, via a loop for example. Each element inside the form is stored as an array element inside elements[]. The syntax is as follows:

document.myform.elements[i] //access the ith form element within the form
document.myform.elements[i].type //Returns the type of the ith form element (ie: "textarea")
document.myform.elements.length //Returns the total number of form elements within form

Properties

Properties Description
elements.length Returns the total number of elements within the form
elements[i].type Returns the type of the referenced form element as a string value (Example):
Possible Type value Note
button  
checkbox  
file  
hidden  
image  
password  
radio  
reset  
select-one Type returns "select-one" for typical selection lists whereby only one option can be selected at one time.
select-multiple Type returns "select-multiple" for selection lists whereby multiple options can be selected at one time. For example:

<select height="3" multiple="yes">
<option>Choice 1</option>
"
</select>

submit  
text  
textarea  

elements[i].property Apart from "type", all properties available to the accessed form element is also available when accessed via the elements object, such as "name", "value" etc.

Examples

Form validation- Check "text" and "textarea" fields for user input

This classic example uses the elements object to generically scan a form and makes sure all text boxes and textareas have text entered before allowing the form to submit:

<script type="text/javascript">

function checkempty(theform){
var returnval=true //by default, allow form submission
for (i=0; i<theform.elements.length; i++){
if (theform.elements[i].type=="text" || theform.elements[i].type=="textarea"){
if (theform.elements[i].value==""){ //if empty field
alert("Please make sure all fields are entered") //alert error message
returnval=false //disallow form submission
break //end loop. No need to continue.
}
}
}
return returnval
}

</script>

<form onSubmit="return checkempty(this)">
Name: <input type="text" name="yourname" /><br />
Email: <input type="text" name="email" /><br />
Comments: <textarea name="comments"></textarea><br />
<input type="submit" value="submit" />
</form>

Output:

Name:

Email:

Comments:


Reference List

Right column

CopyRight (c) 2018 JavaScript Kit. NO PART may be reproduced without author's permission. Contact Info