Text Controls
Forms are devices for collecting information from users and submitting it for processing.
This information can range from crucial input for elaborate information processing systems running
on the Web server to simple user preferences for local page formatting. In either case, forms are
the mechanisms through which users interact with a Web page and through which server and browser
scripts respond to user needs. Forms make interactive Web pages possible.
Web forms contain various types of controls to solicit user input. The following are common
form fields produced with the following HTML tags.
Figure 9-1. Form controls.
Form controls, as a group, often are enclosed inside <form>
tags.
These tags can contain action
and method
attributes governing submission of form values for processing by server scripts.
When form controls are used for input to browser scripts, however, <form>
tags are not required.
The following tutorials describe form controls as data input techniques and devices for trapping user events for browser scripts.
Server processing of form information is beyond the scope of these tutorials.
The Textbox Control
A textbox control is a popular means of soliciting user input to scripts. This input can be
a data value needed for arithmetic or string processing. A textbox presents a single-line input area into which data can be typed. It
is created with the <input type="text">
tag whose
general format is shown below.
<input type="text"
id="id"
value="string"
maxlength="n"
size="n" />
Figure 9-2. General format for <input type="text"> control.
The tag normally includes an id
assignment for reference from
browser scripts. An initial value appearing in the control is given by the
value
attribute. The maximum number of characters that can be entered into the field is
restricted by its maxlength
setting.
A textbox may also include a size
attribute which approximates
the number of characters that can be displayed in the field. The default size is around 20
characters. It is preferable to use the style sheet width
property to
size a textbox. Up to 255 characters can be entered into a textbox, irrespective of its display
size. The textbox scrolls horizontally as additional characters are typed.
There is one special visual variation on a textbox. It can be coded with the attribute
type="hidden"
rather than type="text"
in order to hide the textbox from view. Otherwise, it operates as a standard textbox. The need
to hide a textbox comes up when a script needs a temporary storage area for a value. Its use
is internal to the script and does not need to be seen by the user. Use of a hidden textbox is
demonstrated later.
Textbox Events and Methods
As DOM objects, textboxes support events, event handlers, and methods surrounding their use.
The following table lists selected events,handlers, and methods associated with textbox controls.
Event |
Event Handler
| Description |
blur |
onblur |
The field loses focus when the user tabs from or clicks outside the control. |
focus |
onfocus |
The field gains focus when the user tabs into or clicks inside the control. |
change |
onchange |
The field loses focus after the contents of the control have changed. |
Method |
|
blur() |
Removes focus from the field; does not permit text entry in the control. |
focus() |
Assigns focus to the field; places the cursor in the control. |
select() |
Selects, or highlights, the content of the control. |
Figure 9-3. Selected events, handlers, and methods of textbox control.
The focus and blur Events
The following textbox illustrates its focus and blur events and handlers. When you click inside
the field, a message indicates that your cursor entered the field. When you click outside
the field, a second message indicates that your cursor exited the field.
Figure 9-4. Trapping focus and blur events of a textbox control.
window.onload = init;
function init()
{
var txtMsg = document.getElementById("MSG");
txtMsg.onfocus =TxtFocus;
txtMsg.onblur = TxtBlur;
}
function TxtFocus()
{
document.getElementById('MSG').innerHTML="You entered the field.";
this.value="Click Outside";
}
function TxtBlur()
{
document.getElementById('MSG').innerHTML="You exited the field.";
this.value="Click Here'";
}
<input type="text" value="Click Here" id="txtMsg">
<span id="MSG"></span>
Listing 9-1. Code to trap focus and blur events of a textbox control.
In the first instance, clicking inside the textbox brings focus to the control and raises a
focus event. The onfocus
event handler responds to this event.
It causes a message to be written to the <span>
area,
and the contents of the textbox (its value
property) is changed. In
the second instance, clicking outside the textbox removes focus from it and raises a blur
event. The textbox's onblur
event handler writes an exit message
to the output area, and the contents of the textbox is changed back.
The change Event
A change
event occurs when the contents of a textbox
changes and focus is removed. When you click inside and then outside the following field, nothing
happens. However, if you change one or more characters in the field and click outside,
the change event causes a message to be displayed.
Figure 9-5. Trapping the change event of a textbox control.
function init()
{
var txtChange = document.getElementById("txtChange");
txtChange.onchange = txtChange;
}
function txtChange()
{
document.getElementById("MSG").innerHTML ="You changed the text.";
}
window.addEventListener('load', init, false);
<input type="text" value="Change this text." id="txtChange" />
<span id="MSG"></span>
Listing 9-2. Code to trap the change event of a textbox control.
The textbox's onchange
event handler traps change
events associated with the textbox. In this case, the handler writes a message to the spanned
output area when the textbox's content has changed and focus is removed.
The focus() and blur() Methods
Besides being able to trap and react to focus
and
blur
events, textboxes can produce these events with their focus()
and blur()
methods. As was described previously, a blinking cursor
can be positioned in a textbox by bringing it into focus when the page loads.
function init()
{
document.getElementById('myField').focus()
}
window.addEventListener('load', init, false);
<input type="text" id="myField" />
Listing 9-3. Code to bring focus to a textbox when the page loads.
The select() Method
The select()
method performs, through scripting, the action of
dragging through and selecting text appearing in a textbox. This technique can be used to
automatically select text for replacement, as in the following textbox. When the textbox is
clicked, the entire prompt message is selected for over-typing.
Figure 9-6. Applying the select()
method to a textbox.
function init()
{
var txtSelect = document.getElementById("txtSelect");
txtSelect.onfocus = this.select();
}
window.addEventListener('load', init, false);
<input type="text" value="--Enter your text here--" id="txtSelect" />
Listing 9-5. Code to apply the select()
method to a textbox.
The textarea Control
The properties, methods, and events associated with textbox controls are also recognized by textarea controls.
A textarea is a scrollable field described by the container tag <textarea> </textarea>
. Its general format is shown below.
<textarea
id="id"
cols="n"
rows="n" >
string...
</textarea>
Figure 9-7. General format for textarea control.
The width of the textarea is given by the cols="n"
attribute, where n
is the approximate number of typed characters;
its height is given by the rows="n"
attribute where n
is the number of text lines.
These attributes can be replaced by width
and height
style settings for more control over the exact size of the textarea.
A preloaded text string can be displayed in the control by coding it between the opening and closing tags.
In the following example, text entered into the textarea is converted to upper-case characters
when the control loses focus; a message announces the length of the entered text string.
Figure 9-8. Converting and counting characters entered into a textarea.
function init()
{
var txtInput = document.getElementById("txtInput");
txtInput.onfocus = selectText;
txtInput.onblur = convertCase;
}
function selectText()
{
this.select();
}
function convertCase()
{
this.value = this.value.toUpperCase();
document.getElementById("MSG").innerHTML = "You entered " + this.value.length + " characters";
}
window.addEventListener('load', init, false);
<textarea cols="30" rows="3" id="txtInput">--Enter a text string--</textarea>
<span id="MSG"></span>
Listing 9-6. Code to convert and count characters entered into a textarea.
When focus is brought to the textarea, the prompt text is selected for over-typing with the
select()
method. When focus is removed, the onblur
event handler calls function convertCase()
. The function converts the text string to upper-case characters and reassigns it
to the textarea; a message reporting the length of typed text is displayed.
Validating Data
When relying on users to supply "free-form" information through textboxes and textareas you
should expect errors in data entry. These errors come in the form of
- Missing data
- Too few characters in the field
- Invalid data formats
Prior to running scripts with invalid data that result in JavaScript error messages and aborted
processing, you should validate text entries to make sure they are in the expected formats. The
following sections describe common validation tests that can be performed.
Checking for Missing Data
Text fields should be checked to ensure they contain expected information, that some value
has been entered. These are simple tests for null values. The textbox below is tested for missing
information with an error message displayed along side.
Figure 9-9. Testing a field for missing data.
function init()
{
var btnCheckNull = document.getElementById("btnCheckNull");
btnCheckNull.onclick = checkNull;
}
function checkNull()
{
document.getElementById("MSG").innerHTML = "";
if (document.getElementById("txtField").value == "") {
document.getElementById("MSG").innerHTML = "Missing data!";
}
else {
continue processing...
}
}
window.addEventListener('load', init, false);
<input type="Text" id="txtField">
<input type="button" value="Submit" id="bntCheckNull">
<span id="MSG"></span>
Listing 9-7. Code to test a field for missing data.
The CheckNull()
function is called on the button click. The textbox
is tested for missing characters with an error message displayed on discovering a null field.
Notice that the message area is cleared at the beginning of the function so that any previous
error message is erased when valid data are finally entered.
Checking Text Length
A text field can be tested to determine whether it contains a certain minimum number of characters.
It is easy to control the maximum number of characters entered into a textbox by coding its
maxlength
attribute. However, a minimum number of characters must be
checked by a script. For example, a textarea field is normally expected to contain an extended
number of characters, usually a comment of some sort. Even if the field is not blank, it should probably
contain more than one or two characters. The following script checks to make sure that a textarea
contains at least 20 characters.
Enter comment:
Figure 9-10. Testing a field's character length.
<script>
window.addEventListener('load', init, false);
function init()
{
var btnCheckLength = document.getElementById("btnCheckLength");
btnCheckLength.onclick = checkLength;
}
function checkLength()
{
document.getElementById("MSG").innerHTML = "";
if (document.getElementById("textArea").value.length < 20) {
document.getElementById("MSG").innerHTML = "Please enter a full comment!";
}
else {
continue processing...
}
}
</script>
Enter comment:<br>
<textarea id="textArea"></textarea>
<input type="button" value="Submit" id="btnCheckLength">
<span id="MSG"></span>
Listing 9-8. Code to test a field's character length.
Other tests of this type might involve checking the lengths of Zip codes, Social Security
numbers, telephone numbers, and other such information that should have a fixed or minimum number
of characters.
Checking for Invalid Data Formats
Certain data are expected to be in particular formats. For example, an email address always
contains the "@"
character with ".xxx"
at the end of the string. The following textbox is checked for these characteristics.
Email:
Figure 9-11. Testing for a valid email format.
<script>
window.addEventListener('load', init, false);
function init()
{
var btnCheckEmail = document.getElementById("btnCheckEMail");
btnCheckEmail.onclick = checkEmail;
}
function checkEmail()
{
document.getElementById("MSG").innerHTML = "";
// Check for empty field
if (document.getElementById("email")").value == "") {
document.getElementById("MSG").innerHTML = "Please enter your email address.";
return;
}
// Check for "@" character
var found = false;
for (i=0; i < document.getElementById("email").value.length; i++) {
if (document.getElementById("email").value.charAt(i) == "@") {
found = true;
break;
}
}
if (found == false) {
document.getElementById("MSG").innerHTML = "Missing '@' in email address.";
return;
}
// Check for "." at 4th character from end of string
var dotPos = document.getElementById(email").value.length - 4;
if (document.getElementById("email").value.charAt(dotPos) != ".") {
document.getElementById("MSG").innerHTML = "Missing '.' in email address.";
return;
}
continue processing...
}
</script>
Email: <input type="text" id="email"> <input type="button" value="Submit" id="btnCheckEmail">
<span id="MSG"></span>
Listing 9-9. Code to test for a valid email format.
At the end of each of the three tests a return
statement is issued to
exit the function. When an error is encountered, the script ends; there is no need to continue with additional tests.
In checking for the "@"
character, a loop is set up to scan the length of the entered text.
Each character in turn is matched against the "@"
character.
If the character is found, the loop exits. If it is not found, the loop ends, the found
flag remains false
, and a message is displayed.
The script looks for a "." in the fourth position from the end of the text string. That
position (dotPos
) is calculated from the length of the entered text,
and the if
statement checks for a "." at that particular position.
The above examples certainly do not exhaust the possible validation tests that can be run
against entered data. They are suggestive only, and you will need to determine the type and
strictness of tests needed to keep your scripts from failing when relying on user-entered data.