Introduction to JavaScript

Using Arrays to Refer to Forms

Type something into the text boxes. Then use the first button to see the form element names, and the second button to see the form element values.

First Name:       Last Name:

<SCRIPT>

/*
We loop through all the elements of the Customer Form to determine their names and their values. Since there a 4 form elements, we loop 4 times. Remember that the counting for Arrays start at 0, so we go from 0 - 3 (4 elements). Pay particular attention to 'etc... elements[' + i + '] etc...' We are passing a variable in between a string. NOTE: To do this we need to place the variable where we want it, break up the string and then concatenate the variable to the 2 strings to make one string again.
*/

function DisplayElementNames() {
     for (i = 0; i < 4; i++) {
          alert('document.Customer.elements[' + i + '].name is\n\n"' +
                    document.Customer.elements[i].
name  + '"');    // get form element[i]'s name
     }
}

function DisplayElementContents() {
     for (i = 0; i < 4; i++) {
          alert('document.Customer.elements[' + i + '].value is\n\n"' +
                    document.Customer.elements[i].
value + '"');    // get form element[i]'s value
     }
}

</SCRIPT >

onClick we call the respective functions that initiate the alert messages that either give us all the Form elements' NAMES or VALUES

<FORM NAME="Customer">
    
First Name: <INPUT TYPE="text" NAME="Firstname">
    
Last Name:  <INPUT TYPE="text" NAME="Lastname">
     <INPUT TYPE="button" NAME="Btn1" VALUE="Display the elements names"
       onClick="DisplayElementNames()">
     <INPUT
TYPE="button" NAME="Btn2" VALUE="Display the elements values"
       onClick="DisplayElementContents()">
</FORM >