Last Updated:

Working with forms using Javascript

 

JavaScript is often used to preprocess data entered by users in forms. The validated data can then be passed on to the Web server's CGI extensions. In addition, you can use forms and JavaScript to create active pages that can receive and process arbitrary information from the user.

In the most general form, the <FORM> statement for creating forms in HTML documents is as follows: The NAME parameter specifies the name of the form. This name is required to address the form as a property of the Document object.

<FORM
   NAME="FormName"
   TARGET="WindowName"
   ACTION="Server_Extension_URL"
   METHOD=GET or POST
   ENCTYPE="Data_encoding"
   onSubmit="Submit_event_handler">

   . . .
   defining fields and controls
   . . .
</FORM>

The purpose of the TARGET parameter is similar to the assignment of the same parameter in the <A> statement. When a form is used to pass a request to the Web server's CGI extension, the response received from the server is displayed in a window. The name of this window is specified by the TARGET parameter. If you want the response to appear in the same window as the form, you do not need to specify the TARGET parameter.

The ACTION parameter specifies the URL of the CGI program's boot file, as well as the parameters passed to the extension. If the form is intended to pass data to the Web server extension, the ACTION parameter is required. However, if the data entered in the form is processed locally by JavaScript and is not passed to the Web server, you can omit this parameter.

The METHOD parameter specifies the method to pass data from the form to the Web Server Extension and can accept GET or POST values. If the data from the form fields is processed locally by JavaScript, you do not need to specify the METHOD parameter.

The ENCTYPE parameter specifies the MIME type of the transmitted data and is used very rarely. If the form is intended to pass text data (as is usually the case), this parameter is set to application/x-www-form-urlencoded by default. In this case, the so-called URL encoding is used for the transmitted data. The multipart/form-data data type allows you to transfer both text and binary data. When JavaScript processes data locally, the ENCTYPE parameter is not set.

In addition to the parameters, you can define an event handler for the form that is associated with a button of type SUBMIT. This button is designed to send data from the completed form to the Web server extension. By assigning an event handler, JavaScript can control this process.

 

Properties of the form object

The form object has two sets of properties, one of which is fixed, and the composition of the other depends on which fields and controls are defined on the form. The first set of properties is shown below:

PropertyDescription
actionContains the value of the ACTION parameter
elementsAn array of all the elements (fields and controls) defined in the form
encodingContains the value of the ENCTYPE parameter
lengthElements array size
methodContains the value of the METHOD parameter
targetContains the value of the TARGET parameter

 

Most of the properties of the first set simply reflect the values of the corresponding parameters of the <FORM> operator. You can use them in JavaScript to validate parameters. As for the elements array, it contains objects that correspond to the fields and controls defined in the form. These objects form the second set of properties of the form object:

PropertyDescription
buttonButton with specified caption
checkboxA Switch of type Check Box. Can be used as part of a set of independent switches or separately
hiddenA hidden field that is not displayed. The contents of this field can be read and analyzed by the Web server extension or by JavaScript
passwordA text box for entering passwords. The text typed in this field is not displayed on the screen
radioA radio button for a group of dependent radio buttons. it is typically used to select a single value from several possible values
resetA button that allows the user to reset the contents of input fields and the state of radio buttons to their original state
selectList of arbitrary text strings
submitButton to send data from the completed form to the Web server extension. You can set an arbitrary label for this button
textSingle-line text box
textareaMultiline text box

 

 

Objects that are part of forms

Button button

In general, a button of the button class is defined in a form using the <INPUT operator> as follows:

<INPUT TYPE="button"
   NAME="Button_name"
   VALUE="Label_on_button"
   onClick="Event_Handler">

The TYPE parameter of the operator <INPUT> must be set to button, as shown in the example. The NAME parameter specifies the name of the object that corresponds to the button (not the label on the button). The label on the button is specified using the VALUE parameter. Once you have defined an event handler, you can specify a JavaScript script that will take control after the user clicks on the button.

Properties of the button object

The button object has two properties that reflect the values of the corresponding parameters of the <INPUT> operator:

PropertyDescription
nameValue of the NAME parameter
valueValue of the VALUE parameter

 

Methods of the button object

For the button object, there is only one method that has no parameters - click:

click()

Calling this method has the same effect as left-clicking a button.
 

Sample scenario

An example is a script that handles the clicking of a button labeled Click me on a form. If you click this button, the script displays the button's properties as an object of the button class in the browser window.

Code Listing 3.1.

<HTML>
  <HEAD>
    <TITLE>Button demo</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    function btnClick()
    {
      var szTxt="";
      var szTxt1="";
      szTxt=document.TestForm.bt.value;
      szTxt1=document.TestForm.bt.name;
      document.write("<HR>");     
      document.write("You press button: " + szTxt.bold() 
+ ", name=" + szTxt1.bold());     
      document.write("<HR>");     
    }
    // -->
    </SCRIPT>
  </HEAD>
  <BODY BGCOLOR=white>
    <H1>Click Button</H1>
    <FORM NAME="TestForm">
      <P><INPUT TYPE="button" NAME="bt" VALUE="Click me!"
      onClick="btnClick();">
    </FORM>    
  </BODY>
</HTML>

Checkbox switch

 

Checkbox switches are typically used to select any independent parameters or features. In the form, the checkbox switch is created using the <INPUT> operator with the TYPE parameter equal to the "checkbox" line:

<INPUT TYPE="checkbox"
   NAME="Checkbox_name"
   VALUE="Value"
   CHECKED
   onClick="Event_Handler">
   Text displayed next to the radio button

The NAME parameter specifies the name of the radio button. You can use this name to determine the state of this switch in JavaScript.

You can use the VALUE parameter to specify the string that is passed to the server extension when a completed form is sent, if the switch is in an enabled state. If this parameter is not specified, the string "on" is sent by default. JavaScript can also get the value of the VALUE parameter.

The optional CHECKED parameter is specified if the radio button should be displayed in the enabled state when the form is initially displayed.

If you define an event handler for a radio button, you can specify a JavaScript script that takes control after the user changes the state of the radio button.

Properties of the checkbox object

The checkbox object has several properties that reflect the values of the corresponding parameters of the <INPUT> operator:

PropertyDescription
nameValue of the NAME parameter
checkedA Boolean property that reflects the state of the switch. If the switch is enabled, the property is set to true; otherwise, false. a script can use this property to change the state of the switch
valueValue of the VALUE parameter
defaultCheckedA Boolean property that reflects the value of the CHECKED parameter. If the CHECKED parameter is present in the radio button definition, the property is set to true; otherwise, false. The script can set or set the value of this property

 

Methods of the checkbox object

A single click method is defined for the checkbox object that has no parameters:

click()

When this method is called, the switch is set to the enabled state.

 

Radio Switch

Radio radio switches are used when you want to organize the choice of one of several options. Based on this, several such switches are usually located in the form. The definition of the radio switch is as follows:

<INPUT TYPE="radio"
   NAME=" Radio_switch_name"
   VALUE="Value"
   CHECKED
   onClick="Event_Handler">
   Text displayed next to the radio button

The purpose of the NAME, VALUE, and CHECKED parameters of the radio switch is the same as the assignment of similar parameters to the checkbox switch. The difference is that all radio radio radio switches that belong to the same group must have the same name, as defined by the NAME parameter. As for checkbox switches, if there are several of them, then they should all be called differently. In order for the Web server extension or JavaScript that processes the form to know which of the radio group radio buttons is in the enabled state, all such radio switches must have different VALUE values. In addition, only one of the radio radio radio switches can be defined with the CHECKED parameter.

Properties of the radio object

The radio object has the following properties:

PropertyDescription
nameValue of the NAME parameter
checkedA Boolean property that reflects the state of the switch. If the switch is enabled, the property is set to true; otherwise, false. a script can use this property to change the state of the switch
lengthNumber of radio radio radio switches defined in the group with the name specified by the NAME parameter
valueValue of the VALUE parameter
defaultCheckedA Boolean property that reflects the value of the CHECKED parameter. If the CHECKED parameter is present in the radio button definition, the property is set to true; otherwise, false. The script can set or set the value of this property

 

Methods of the radio object

 

For the radio object, a click method is defined that has no parameters:

click()

 

When you call this method, a radio button is selected to work with.

Example of a form with radio buttons

 

This topic provides the source code for an HTML document with script designed to dynamically create a new page by using JavaScript. The settings on this page are determined by the state of the checkbox and radio radio switches located in this document.

Our document contains one form, which has three independent-commit checkbox radio buttons (located in the Page elements group), three radio buttons with a dependent commit (forming a Text color group), and two buttons, Create Page and Reset.

If the Show title radio button is enabled, the HTML document generated by the JavaScript will be labeled. When you turn on the Show horizontal lines radio button, the information about the status of the radio buttons displayed in the document will be highlighted at the top and bottom with horizontal dividing lines. The Table view radio button affects how information is displayed. If it is enabled, the information will be displayed in tabular form, and if it is turned off, it will be displayed as a list.

The radio buttons of the Text color group, located in the original HTML document, specify the color of the rows when displaying information as a list or the color of the radio button names when displayed in a table. At the bottom of the form are two buttons labeled Create Page and Reset. If you click on the first of these buttons, a JavaScript function is invoked that will determine the current state of the radio buttons and generate a new HTML document. This document appears in a browser window instead of the original one. Use the Reset button to set the initial state of the switches. The text of the HTML document with the script that performs all of the above steps is shown in Listing 3.2.

Code Listing 3.2.

<HTML>
  <HEAD>
  <SCRIPT>
    <!--
    function resetRCHBox()
    {
      bTitle=false;
      bHorzLine=false;
      bTable=false;
      szColor="Red";
    }

    function chkRadio(form,value)
    {
      szColor = value;
    }

    function btnClick(form)
    {
      var szTxt="";

      document.write("<HEAD></HEAD><BODY>");     

      if(bTitle)
        document.write("<H1>Switches Checkbox and Radio</H1>");     

      if(bHorzLine)
        document.write("<HR>");     

      if(bTable)
      {
        document.write("<TABLE>");     

        szTxt=" " + bTitle;
        document.write("<TR><TD><FONT COLOR=" + szColor 
+ ">Title:</TD><TD>" + szTxt.bold() + "</TD></TR>");     

        szTxt=" " + bHorzLine;
        document.write("<TR><TD><FONT COLOR=" + szColor 
+ ">HorzLine:</TD><TD>" + szTxt.bold() + "</TD></TR>");     

        szTxt=" " + bTable;
        document.write("<TR><TD><FONT COLOR=" + szColor 
+ ">Table:</TD><TD>" + szTxt.bold() + "</TD></TR>");     

        document.write("<TR><TD><FONT COLOR=" + szColor 
+ ">Color:</TD><TD>" + szColor.bold() + "</TD></TR>");     

        document.write("</TABLE>");     
      }
      else
      {
        document.write("<FONT COLOR=" + szColor + ">");     

        szTxt=" " + bTitle;
        document.write("<BR>Title: " + szTxt.bold());     

        szTxt=" " + bHorzLine;
        document.write("<BR>HorzLine: " + szTxt.bold());     

        szTxt=" " + bTable;
        document.write("<BR>Table: " + szTxt.bold());     

        document.write("<BR>Color: " + szColor.bold());     

        document.write("</FONT>");     
      }

      if(bHorzLine)
        document.write("<HR>");     

      document.write("</BODY>");     
    }
    // -->
  </SCRIPT>
    <TITLE>Переключатели checkbox и radio</TITLE>
  </HEAD>
  <BODY>
  <SCRIPT>
    <!--
    var bTitle=false;
    var bHorzLine=false;
    var bTable=false;
    var szColor="Red";
    // -->
  </SCRIPT>
    <FORM NAME="myform">
     <B>Page elements:</B>

     <P><INPUT TYPE="checkbox" NAME="chkTitle"
        onClick="if(this.checked) {bTitle=true;}"> Show title

     <BR><INPUT TYPE="checkbox" NAME="HorzLine"
        onClick="if(this.checked) {bHorzLine=true;}"> Show horizontal lines

     <BR><INPUT TYPE="checkbox" NAME="Table"
        onClick="if(this.checked) {bTable=true;}"> Table view

     <P><B>Text color:</B>

     <P><INPUT TYPE="radio" NAME="Color" CHECKED VALUE="Red"
        onClick="if(this.checked) {chkRadio(this.form,this.value);}"> Red

     <BR><INPUT TYPE="radio" NAME="Color" VALUE="Green"
        onClick="if(this.checked) {chkRadio(this.form,this.value);}"> Green

     <BR><INPUT TYPE="radio" NAME="Color" VALUE="Blue"
        onClick="if(this.checked) {chkRadio(this.form,this.value);}"> Blue

     <TABLE>
       <TR><TD><INPUT TYPE="button" NAME="btn" VALUE="Create Page"
       onClick="btnClick(this.form);"></TD>

       <TD><INPUT TYPE="reset" NAME="resetBtn" VALUE="Reset"
        onClick="resetRCHBox();"></TD></TR>
     </TABLE>
    </FORM>
  </BODY>
</HTML>

Select list

By using the <SELECT> operator, you can place a list inside a form that allows you to select one row or view multiple lines. The format of the <SELECT> operator is as follows:

<SELECT NAME="select_list_name"
    SIZE="List_Size"
    MULTIPLE
    onBlur="EventHandler"
    onChange="EventHandler"
    onFocus="EventHandler">
    <OPTION VALUE="Value" SELECTED> Text
    <OPTION VALUE="Value"> Text
    ...
    <OPTION> Text
</SELECT>

All parameters of the <SELECT> statement are optional, but in order for JavaScript to work with the list, you must specify at least a NAME parameter that specifies the name of the list.

The SIZE parameter specifies the size of the visible portion of the list in rows.

If the optional MULTIPLE parameter is specified, the select object is a browse list, not a choice list.

To define list items, use the <OPTION> operator. The <OPTION> operator can have two parameters, VALUE and SELECTED. The VALUE parameter specifies the value that is passed to the Web server extension. The SELECTED parameter marks the list line that is highlighted by default when the form is initially displayed. The <OPTION> statement is followed by the text displayed in the list lines.

Properties of the select object

The following are the properties of the select object that are available to JavaScript:

PropertyDescription
lengthNumber of items (rows) in the list
nameValue of the NAME parameter
optionsAn array of options objects that correspond to the array elements specified by the <OPTION operator>
selectedIndexThe number of the selected item or first item among several selected items (if the MULTIPLE option is specified and the user has selected multiple items in the list)

 

One of the properties of the select list is the options array. This array stores the list items defined by the <OPTION> operator. Each element of such an array is nothing more than an object with the following set of properties:

PropertyDescription
defaultSelectedReflects the status of the SELECTED parameter
indexOrdinal number (index) of a list item
lengthNumber of items in the selected object
nameValue of the NAME parameter
selectedJavaScript can use the selected property to select this element
selectedIndexThe number of the selected item
textThe text that follows the <OPTION statement>
valueValue of the VALUE parameter

 

Methods of the select object

 

Two methods are defined for the select object that have no parameters, focus and blur. The first of these methods allows you to pass input focus to the list, and the second allows you to take that focus away from the list.

Event handlers associated with the select object

 

As you can see from the <SELECT operator format> discussed above, you can define three event handlers for the list: onFocus, onBlur, and onChange. The onFocus and onBlur events are raised when the list gains and loses input focus, respectively. As for the onChange event, it is created when the user changes the state of the list, that is, selects another item in the list.

Example of a script that works with a list

 

When working with lists from JavaScript, it is most common to want to determine which items have been selected by the user. This example shows two lists. The first of them is designed to select a color, and the second is the size of some object (in this case, it does not matter which one). Lists differ in the number of items that are visible at the same time. In order to see all the items in the size list, you can use the preview bar located on the right side of this list.

 

In addition to the lists, the form has two buttons labeled Complete and Reset. The Reset button returns the lists to their original state as they were in immediately after the HTML document was displayed. If you click on the Complete button, the control will receive a JavaScript script that will display the selected color and size on the screen as a dialog bar with a message.

Code Listing 3.3.

<HTML>
  <HEAD>
    <TITLE>Working with lists</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    function Complete()
    {
      varszElement="";
      szElement="Color: " +
        Sel.ColorList.options[Sel.ColorList.selectedIndex].value +
        "(" + Sel.ColorList.selectedIndex + ")" +
        "\nSize: " +
        Sel.SizeList.options[Sel.SizeList.selectedIndex].value +
        "(" + Sel.SizeList.selectedIndex + ")";

      alert(szElement);
    }
    // -->
    </SCRIPT>
  </HEAD>
  <BODY BGCOLOR=white>
    <H1>Working with lists</H1>

    <FORM NAME="Sel">
      <P>Select color:<P>
      <SELECT NAME="ColorList">
        <OPTION VALUE=Black SELECTED> Black
        <OPTION VALUE=White> White
        <OPTION VALUE=Red> Red
        <OPTION VALUE=Orange> Orange
        <OPTION VALUE=Yellow> Yellow
        <OPTION VALUE=Green> Green
        <OPTION VALUE=Blue> Blue
        <OPTION VALUE=Blue> Blue
        <OPTION VALUE=Purple> Purple
      </SELECT>

      <P>Select size:<P>
      <SELECT NAME="SizeList" SIZE=3>
        <OPTION VALUE=Standard SELECTED> Standard
        <OPTION VALUE=Large> Large
        <OPTION VALUE=Medium> Medium
        <OPTION VALUE=Small> Small
        <OPTION VALUE=Very_small> Very small
      </SELECT>
      <P>
      <table>
        <TR><TD><INPUT TYPE="button" VALUE="Complete"
        onClick="Complete();"></TD>

        <TD><INPUT TYPE="reset" VALUE="Reset"></TD></TR>
      </TABLE>
    </FORM>
  </BODY>
</HTML>

Single-line text field

 

Perhaps the most common form on Web server pages is single-line fields for entering and editing text. In order to embed such a field in the form, you must use the <INPUT> operator with the TYPE parameter equal to the "text" value:

<INPUT TYPE="text"
   NAME="Field_name_text"
   VALUE="Value"
   SIZE=Field_size
   onBlur="EventHandler"
   onChange="EventHandler"
   onFocus="EventHandler"
   onSelect="EventHandler">

The NAME parameter allows you to specify the field name that is required to access the properties of the text object corresponding to that field.

You can use the VALUE parameter to write an arbitrary text string to the field. This string will be displayed as soon as the HTML document is loaded into the browser window.

The SIZE parameter specifies the size (width) of the text box in characters. This is the size of the visible part of the field. It does not limit the length of the string that can be entered in this field.

Properties of the text object

JavaScript has access to three properties of the edit field as an object of the text class:

PropertyDescription
defaultValueReflects the state of the VALUE parameter
nameValue of the NAME parameter
valueCurrent contents of the edit field

 

As soon as the edit fields are displayed, the defaultValue and value properties store the same rows. When the user edits the text, all changes are reflected in the value property. Note that by changing the contents of the value property, JavaScript can change the contents of the edit field.

Methods of the text object

The focus, blur, and select methods are defined for the text object and have no parameters. With the focus method, JavaScript can pass focus to the editing field, and using the blur method, it can take the focus away from the field. Calling the select method highlights the contents of the edit field.

Event handlers for the text object

Event handlers are called in the following cases:

HandlerWhen called
onFocusCalled when the edit field receives input focus
onBlurCalled when the edit box loses input focus
onChangeWhen you change the contents of an edit field
onSelectWhen you select the contents of an edit field

 

Example (questionnaire verification)

Let's consider the method of working with text fields in JavaScript scripts using the example of an HTML document with a form for entering a questionnaire.

Our script performs simple processing of information that is entered in the text fields of this form. Specifically, the script converts last name characters to uppercase characters. If you specify an age less than 18 years, the scenario will make it equal to zero. If you click the Complete button after filling out the questionnaire, a dialog bar will appear on the screen that displays the contents of the individual fields of the form. The Reset button resets the fields to their original state.

Code Listing 3.4.

<HTML>
  <HEAD>
    <TITLE>Working with text fields</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    function Complete()
    {
      varszElement="";
      szElement="Last name: " + Sel.family.value +
        "\nName: " + Sel.Name.value +
        "\nPhone: " + Sel.PhoneNumber.value +
        "\nAge: " + Sel.Age.value;

      alert(szElement);
    }
    function CheckAge(age)
    {
      if(age < 18)
        return "0";
      else
        return age;
    }
    // -->
    </SCRIPT>
  </HEAD>
  <BODY BGCOLOR=white>
    <H1>Fill out the questionnaire</H1>

    <FORM NAME="Sel">
      <table>
       <TR><TD><B>Last name:</B></TD><TD><INPUT TYPE="text"
        NAME="family"
        onChange="this.value=this.value.toUpperCase()"
        SIZE="20" ></TD></TR>

      <TR><TD><B>Name:</B></TD><TD><INPUT TYPE="text"
        NAME="Name" SIZE="20"></TD></TR>

      <TR><TD><B>Phone:</B></TD><TD><INPUT TYPE="text"
        NAME="PhoneNumber" SIZE="10"></TD></TR>

      <TR><TD><B>Age:</B></TD><TD><INPUT TYPE="text"
        NAME="Age" VALUE="18" SIZE="4"
        onChange="this.value=CheckAge(this.value)"
        onFocus="this.select()"
        ></TD></TR>
      <P>
      <table>
        <TR><TD><INPUT TYPE="button" VALUE="Complete"
        onClick="Complete();"></TD>

        <TD><INPUT TYPE="reset" VALUE="Reset"></TD></TR>
      </TABLE>
    </FORM>
  </BODY>
</HTML>

Multiline textarea field

In cases where editable text must span multiple lines, a multiline text field is placed between the <TEXTAREA> and </TEXTAREA statements> in the form:

<TEXTAREA
   NAME="Field_name_textarea"
   ROWS="Number_rows"
   COLS="Number_columns"
   WRAP="Text_fold_mode"
   onBlur="EventHandler"
   onChange="EventHandler"
   onFocus="EventHandler"
   onSelect="EventHandler">
   . . .
   Display text
   . . .
</TEXTAREA>

Here, using the NAME parameter, you must specify the name of the field. It is required so that JavaScript can access the properties and methods of this field.

The ROWS and COLS parameters determine the apparent size of a multiline edit field by specifying, respectively, the number of rows and columns (the number of characters that can fit in a single row).

The WRAP parameter specifies how text is rolled up and can have one of the following three values:

MeaningText wrapping method
offConvolution is disabled and rows are displayed as they are entered
virtualStrings are collapsed only when displayed in the edit window, but are passed to the Web server extension and JavaScript exactly as they are entered
physicalwhen you roll up newline characters are written to the text that is passed

 

Methods of the textarea object

 

The textarea object has the same methods defined as the text object. These are focus, blur, and select methods that have no parameters. With the focus method, JavaScript can pass focus to the editing field, and using the blur method, it can take the focus away from the field. Calling the select method highlights the contents of the multiline edit field.

Textarea Object Event Handlers

 

Event handlers are called in the following cases:

HandlerWhen called
onFocusCalled when the edit field receives input focus
onBlurCalled when the edit box loses input focus
onChangeWhen you change the contents of an edit field
onSelectWhen you select the contents of an edit field

 

Example of a script that populates a textarea field

A multi-line editing field is located in the forms so that the user can write in it his feedback, comment, question or similar information. With JavaScript, it's easy to pre-populate a field with some text.

For example, suppose you want to create a form that is designed to send feedback about the operation of a program via the Internet. If you turn on the "Thank you" radio button, the script will automatically record in the edit field the date and time when the review was prepared, as well as the text of the positive review. Only a signature will be added to this text.

In order to inform the manufacturer of the program about errors, turn on the "Problems" switch. Immediately after that, the script will write the text of the corresponding message in a multiline field. This text will need to be edited and supplemented, describing, for example, the external manifestations of the detected error.

Code Listing 3.5.

<HTML>
  <HEAD>
    <TITLE>Working with a multiline text field</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    var szOK = "Thank you!\nYour program is running without errors.";
    var szTrouble = "Sorry, we're having trouble with your program.";
    var szProbList = "\nProgram serial number: XXXXXX\nPurchase date: XX-XX-XX";

    function getDate()
    {
      var szDate = "";
      szDate = new Date();
      return szDate.toLocaleString() + "\n";
    }

    function chkRadio(form,value)
    {
      if(value == "Thanks")
        Sel.Comment.value = getDate() + szOK;
      else
        Sel.Comment.value = getDate() + szTrouble + szProbList;
    }
    function init()
    {
        Sel.Comment.value = getDate() + szOK;
    }

    function Complete()
    {
      szMsg = Sel.Comment.value;
      alert(szMsg);
    }
    // -->
    </SCRIPT>
  </HEAD>
  <BODY BGCOLOR=white>
    <H1>Submit your review</H1>

    <FORM NAME="Sel">

      <P><INPUT TYPE="radio" NAME="TextSelect" CHECKED VALUE="Thanks"
        onClick="if(this.checked) {chkRadio(this.form,this.value);}"> Thanks

      <BR><INPUT TYPE="radio" NAME="TextSelect" VALUE="Trouble"
        onClick="if(this.checked) {chkRadio(this.form,this.value);}"> Issues

      <P><TEXTAREA NAME="Comment"
        ROWS="8" COLS="40" WRAP="physical">
      </TEXTAREA>

      <P><INPUT TYPE="button" VALUE="Complete" onClick="Complete();">

    </FORM>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
      init();
    // -->
    </SCRIPT>
  </BODY>
</HTML>

 

Single-line password field

To enter information such as passwords, forms place single-line edit fields of the password type:

<INPUT TYPE="password"
   NAME="Field_name_text"
   VALUE="Value"
   SIZE=Field_Size>

For the password field, you can specify the NAME, VALUE, and SIZE parameters. Note that this field cannot have event handlers.

The NAME parameter specifies the field name that is required to access the properties of the password object corresponding to that field.

You can use the VALUE parameter to write an arbitrary text string to the field.

The SIZE parameter specifies the size (width) of the text box in characters. This is the size of the visible part of the field. It does not limit the length of the string that can be entered in this field.

The password field is similar to the text field discussed earlier. The main difference is that the characters of the text entered in this field are replaced with asterisks.

Properties of the password object

 

JavaScript has access to three properties of the password edit field:

PropertyDescription
defaultValueReflects the state of the VALUE parameter
nameValue of the NAME parameter
valueCurrent contents of the edit field

 

As with the text field, as soon as the edit field is displayed, the defaultValue and value properties store the same rows. When the user edits the text, all changes are reflected in the value property. By modifying the contents of the value property, the script can change the contents of an edit field of type password.

Methods of the password object

 

The password object has defined focus, blur, and select methods that have no parameters. With the focus method, JavaScript can pass focus to the editing field, and using the blur method, it can take the focus away from the field. Calling the select method highlights the contents of the edit field.

Example (enter ID and password)

 

As a practical example of using JavaScript to process information from the text and password fields, here is an HTML document designed for user registration.

In the registration form, the new user must enter his ID, as well as set a password. It's easy to make a mistake in the password process, so registration systems usually require you to enter a new password twice. If the same password is entered both times, it becomes active for that user.

Our script, which processes data from a form, solves two problems. First, it converts user ID characters to uppercase characters. Second, the script verifies that the passwords entered in the Password and Password Verification fields are identical. If the entered passwords are identical, then after clicking on the Complete button, the user will see a dialog bar with the entered ID and password on the screen. If the passwords do not match, the script prompts the user to re-enter the passwords.

Code Listing 3.6.

<HTML>
  <HEAD>
    <TITLE>Entering and verifying a password</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    function Complete()
    {
      if(Sel.pwd.value != Sel.pwd1.value)
        alert("Error entering password\nPlease try again");
      else
      {
        varszId="";
        varszPwd="";
        szId = Sel.id.value;
        szPwd = Sel.pwd.value;
        alert("Registration completed:\n" + "ID=" +
          szId + "\nPassword=" + szPwd);
      }
    }
    // -->
    </SCRIPT>
  </HEAD>
  <BODY BGCOLOR=white>
    <H1>Register</H1>

    <FORM NAME="Sel">
      <table>
       <TR><TD><B>Identifier:</B></TD><TD><INPUT TYPE="text"
        NAME="id" onChange="this.value=this.value.toUpperCase()"
        SIZE="20" ></TD></TR>

      <TR><TD><B>Password:</B></TD><TD><INPUT TYPE="password"
        NAME="pwd" SIZE="20"></TD></TR>

      <TR><TD><B>Password verification:</B></TD><TD><INPUT TYPE="password"
        NAME="pwd1" SIZE="20"></TD></TR>
      </TABLE>
      <P>
      <table>
        <TR><TD><INPUT TYPE="button" VALUE="Complete"
        onClick="Complete();"></TD>

        <TD><INPUT TYPE="reset" VALUE="Reset"></TD></TR>
      </TABLE>
    </FORM>
  </BODY>
</HTML>