<form name="formOne">Take a look at three different ways to code the path to the first form element in the first form on a page.
<input type="text" name="elementOne">
</form>
document.formOne.elementOneFor standards compliant browsers using the HTML attribute ID, there is yet another path:
document.forms[0].elements[0]
document.forms["formOne"].elements["elementOne"]
<input type="text" id="elementOne">Since CGI scripts require name/value pairs (not ID/value pairs) from forms, and for the sake of code compatibility between the painfully uneven support amongst varying browsers, these tutorials do not use the latter convention when dealing with forms and form elements.
document.getElementById("elementOne")
<form>The function that displays the names only:
<input type="text" size="15" value="Hello World" name="elmOne">
<input type="checkbox" name="elmTwo" checked>
<textarea name="elmThree">Small textarea</textarea>
<select name="elmFour">
<option selected> Yellow
<option> Green
</select>
<input type="button" onclick="elmName()" name="elmFive" value="Display Names">
<input type="button" onclick="elmLoop()" name="elmSix" value="Display Properties and Values">
</form>
function elmName(){And the function displaying the various properties and values:
for(i=0; i<document.forms[0].elements.length; i++){
alert(document.forms[0].elements[i].name)
}
}
function elmLoop(){So you see, you can get as complex and specific as you need to be, but the basis of it all is a simple loop through the elements array. See Netscape's DevEdge Chapter 7 Documentation for more element objects and properties.
var theForm = document.forms[0]
for(i=0; i<theForm.elements.length; i++){
var alertText = ""
alertText += "Element Type: " + theForm.elements[i].type + "\n"
if(theForm.elements[i].type == "text" || theForm.elements[i].type == "textarea" || theForm.elements[i].type == "button"){
alertText += "Element Value: " + theForm.elements[i].value + "\n"
}
else if(theForm.elements[i].type == "checkbox"){
alertText += "Element Checked? " + theForm.elements[i].checked + "\n"
}
else if(theForm.elements[i].type == "select-one"){
alertText += "Selected Option's Text: " + theForm.elements[i].options[theForm.elements[i].selectedIndex].text + "\n"
}
alert(alertText)
}
}