Create a script that automatically moves a user’s cursor to the next field after a
specified number of characters have been entered into the current Held.
The exercise uses a simple form that allows users to enter their 10—digit telephone
number. The form will contain three text boxes for the area code, exchange, and number
portions of the telephone number.
1. Create a new HTML document in your text editor and use “Auto Next Field" as the
content of the <title> element and the following html tags.
<html>
<head>
<title>Auto Next Field</title>
</head>
<body>
</body>
</html>
2. ln the document body, add the following form that contains three text boxes. The first
two text boxes, for the area code and exchange, use the onkeyup event to call an event
handler function named nextField (). Two arguments are passed to the nextField()
function: a this reference, which passes the name of the current control, and the name
of the destination control. Notice that each of the text boxes includes maxlength
attributes.
<form action="FormProcessor.html" method="get"
enctype="application/x-www-form-urlencoded">
<p><strong>Enter your 10-digit telephone number:</strong>
<input type="text" name="area_code" size="4"
onkeyup="nextField(this, document.forms[0].exchange)"
maxlength="3" />
<input type="text" name="exchange" size="4"
onkeyup="nextField(this, document.forms[0].number)"
maxlength="3" />
<input type="text" name="number" size="5" maxlength="4" /></p>
</form>
3. Add a script section to the document head with the nextField() function, which is
called from the on keyup events in the <input> elements. Notice how the conditional
expression compare the length of the field to the maxLength property. The current value
assigned to the field is retrieved with the value property. Then, a property named length
is appended to the value property. The length property is a property of the String class,
and it returns the number of characters in a string. if the length of the field is equal to
the value assigned to the maxLength property, the focus () statement moves the
focus to the field identified by the destField parameter.
<script type="text/javascript">
/* <! [CDATA[ */
/* ]]> */
function nextField(startField, destField) {
if (startField.value.length==startField.maxLength)
destField.focus();
}
</script>