<form action = ""> <input type = "button" name = "pushMe" /> </form>
document.forms[0].elements[0]
Problem: document changes
e.g. if new button were added before the pushMe
button
in the form, the DOM address shown would be wrong.
<form name = "myForm" action = ""> <input type = "button" name = "pushMe" /> </form> document.myForm.pushMe
<form action = ""> <input type = "button" id = "pushMe" /> </form> document.getElementById("pushMe")
getElementById
is a method (or function) of the document object.
This means you can only access it by using document.getElementById
.
<form id = "topGroup"> <input type = "checkbox" name = "toppings" value = "olives" /> ... <input type = "checkbox" name = "toppings" value = "tomatoes" /> </form> ... var numChecked = 0; var dom = document.getElementById("topGroup"); for (index = 0; index < dom.toppings.length; index++) if (dom.toppings[index].checked]) numChecked++;
<!DOCTYPE html> <!-- first form --> <html lang = "en"> <head> <title> Our first form </title> <meta charset = "utf-8" /> <style type = "text/css"> label, input {display: block; margin-bottom: 15px;} label { float: left; width:80px; text-align: right;} input { margin-left:100px;} </style> <script type = "text/javascript"> <!-- function getInfo(form) { var first = form.elements[0].value; //or var first = form.firstname.value; //or var first = myform.firstname.value; var last = form.elements[1].value; //or var last = form.second.value; //or var last = document.getElementById("second").value; var outString=first + " " + last + ", nice to meet you.<br />"; /* document.write(outString); */ //This statement will be on the new screen. document.getElementById("info").innerHTML = outString; //Write it on the same screen as the form } //--> </script> </head> <body> <h2>Enter your information</h2> <form name= "myform"> <label>First name:</label> <input type="text" name="firstname" id="first" /> <label>Last name:</label> <input type="text" name="lastname" id="second" /> <input type = "button" value="Done" onClick = "getInfo(this.form)"> <input type ="reset" value = "reset the form" /> </form> <p id="info"></p> </body> </html>Checking data and Taking input Calculate Miles Per Gallon