Here we will access the value in a textbox called test on a form called example.
We can use either the Name method or the Dom method.
Name method - window.document.example.test.value
or
Dom method -window.document.forms[0].elements[0].value
providing the text box is the first element on the first form.
<body>
<form action="" name="example" id="example" >
<input type="text" value="fred derf" name="test" id="test" />
</form>
<a href="#" onclick="alert(document.example.test.value);">
Check value in the text box</a>
</body>
<head> <script type='text/javascript'>
<!--
function textboxbyname(){
alert(document.example.test.value);
}
function textboxbydom(){
alert(document.forms[0].elements[0].value);
}
-->
</script> </head>
<body>
<h2>Accessing Form Elements and their Contents</h2>
<form action="" name="example" id="example" >
<input type="text" name="test" id="test" />
Type something into the text box.
<input type='button' name='button1' value='press me to test access by name' onclick='textboxbyname();'
/>
<input type='button' name='button2' value='press me to test access by dom' onclick='textboxbydom();'
/>
</form>
</body>
Exercise 1
Create a form with 2 textboxes and a button.
Fill in one text box and use the button to copy the result to the other textbox.
Exercise 2
Create a webpage with three text boxes.
Write the code that multiplies the contents of the first two text boxes and
displays the result in the third.