Controlling Data Entry Using Form Fields
Creating 'Encoded' Name & Value Pairs
Passing data from one form to another
Addressing Form Field Validation with Regular Expressions and JavaScript 1.2
You are here: irt.org | Articles | JavaScript | Form | Chapter 6: Beginning JavaScript [ previous next ]
Published on: Sunday 29th April 2001 By: Paul Wilton
The standard text element allows users to enter a single line of text. This information can then be used in JavaScript code, or be submitted to a server for server-side processing.
A text box is created using the <INPUT> tag, much as our button was, but by setting the TYPE attribute to text. Again, you can choose not to include the VALUE attribute, but if you do include it, then this value will appear inside the text box when the page is loaded.
In the example below, the <INPUT> tag has two additional attributes of SIZE and MAXLENGTH. The SIZE attribute determines how many characters wide the text box is, and MAXLENGTH determines the maximum number of characters the user can enter into the box. Both attributes are optional and use defaults determined by the browser.
For example, to create a text box 10 characters wide, with a maximum character length of 15, and initially containing the words 'Hello World', our <INPUT> tag would be as follows:
<INPUT TYPE="text" NAME="myTextBox" SIZE=10 MAXLENGTH=15 VALUE="Hello World">
The Text object that this element creates has a value property, which we can use in our scripting to set or read the text contained inside the text box. In addition to the common properties and methods we discussed earlier, the Text object also has the select() method, which selects or highlights all the text inside the text box. This may be used if the user has entered an invalid value, and we can set the focus to the text box and select the text inside it. This then puts the user's cursor in the right place to correct the data and makes it very clear to the user where the invalid data is.
The value property of Text objects always returns a string data type, even though it may be that number characters are being entered. If we use the value as a number then JavaScript normally does a conversion from a string data type to a number data type for us, but this is not always the case. For example, JavaScript won't do the conversion if the operation you're doing is valid for a string. If we have a form with two text boxes and we added the values returned from these, JavaScript will concatenate rather than add the two values, so 1 + 1 will be 11 and not 2. To fix this, we need to convert all the values involved to numerical data type, for example by using parseInt() or parseFloat(). However, if we subtracted the two values, an operation only valid for numbers, then JavaScript says "ah ha this can only be done with numbers so I'll convert the values to a number data type". So, 1 - 1 will be returned as 0 without using parseInt() or parseFloat(). This is a tricky bug to spot, so it's best to get into the habit of converting explicitly to save problems later.
As well as the common event handlers such as onfocus and onblur, the Text object also has the onchange, onselect, onkeydown, onkeypress, and onkeyup event handlers.
The onselect event fires when the user selects some text in the text box.
More useful is the onchange event which fires when the element loses focus if (and only if) the value inside the text box is different from the value it had when it got the focus. This enables us to do things like validity checks that occur only if something has changed.
As mentioned before, the onfocus and onblur events can be used for validating user input. However, they also have another purpose and that's to make a text box read-only. In IE 4.0+ and NN 6 we can use the READONLY attribute of the <INPUT> tag or the readOnly property of the Text object to prevent the contents being changed. However, this won't work on NN 4.x. We can get around this using the blur() method. All we need do is add an onfocus event handler to the <INPUT> tag defining the textbox, and connect it to some code that blurs the focus from the text box with the blur() method:
<INPUT TYPE="text" NAME=txtReadonly VALUE="Look but don't change" onfocus="window.document.form1.txtReadonly.blur()" READONLY=true>
The onkeypress, onkeydown, and onkeyup events fire, as their names suggest, when the user presses a key, when they press a key down, and when a key pressed down is let back up.
Let's put all the above information on text boxes and buttons together into an example. In this example we have a simple form consisting of two text boxes and a button. The top text box is for the user's name, the second for their age. We do various validity checks. We check the validity of the age text box when it loses focus. However, the name and age text boxes are only checked to see if they are empty when the button is clicked.
<HTML> <HEAD> <SCRIPT LANGUAGE=JavaScript> function butCheckForm_onclick() { var myForm = document.form1; if (myForm.txtAge.value == "" || myForm.txtName.value == "") { alert("Please complete all the form"); if (myForm.txtName.value == "") { myForm.txtName.focus(); } else { myForm.txtAge.focus(); } } else { alert("Thanks for completing the form " + myForm.txtName.value); } } function txtAge_onblur() { var txtAge = document.form1.txtAge; if (isNaN(txtAge.value) == true) { alert("Please enter a valid age"); txtAge.focus(); txtAge.select(); } } function txtName_onchange() { window.status = "Hi " + document.form1.txtName.value; } </SCRIPT> </HEAD> <BODY> <FORM NAME=form1> Please enter the following details: <P> Name: <BR> <INPUT TYPE="text" NAME=txtName onchange="txtName_onchange()"> <BR> Age: <BR> <INPUT TYPE="text" NAME=txtAge onblur="txtAge_onblur()" SIZE=3 MAXLENGTH=3> <BR> <INPUT TYPE="button" VALUE="Check Details" NAME=butCheckForm onclick="butCheckForm_onclick()"> </FORM> </BODY> </HTML>
After you've entered the text, save the file as ch6_examp4.htm and load it into your web browser.
Type your name into the name text box. When you leave the text box you'll see Hi yourname appear in the status bar at the bottom of the window.
Enter an invalid value into the age text box, such as 'aaaa', and when you try to leave the box it'll tell you of the error and send you back to correct it.
Finally click the Check Details button and both text boxes will be checked to see that you have completed them. If either is empty, you'll get a message telling you to complete the whole form and it'll send you back to the box that's empty.
If everything is filled in correctly, you'll get a message thanking you.
Note that, at the time of writing, this example does not work properly on NN 6.
Within the body of the page, we create the HTML tags that define our form. Inside our form, which is called form1, we create the three form elements with names txtName, txtAge, and butCheckForm.
<FORM NAME=form1> Please enter the following details: <P> Name: <BR> <INPUT TYPE="text" NAME=txtName onchange="txtName_onchange()"> <BR> Age: <BR> <INPUT TYPE="text" NAME=txtAge onblur="txtAge_onblur()" SIZE=3 MAXLENGTH=3> <BR> <INPUT TYPE="button" VALUE="Check Details" NAME=butCheckForm onclick="butCheckForm_onclick()"> </FORM>
You'll see that for the second text box, that is the txtAge text box, we have included the SIZE and MAXLENGTH attributes inside the <INPUT> tag. Setting the SIZE attribute to 3 gives the user an idea of how much text we are expecting, and setting the MAXLENGTH attribute to 3 helps ensure that we don't get too large numbers entered for our age value!
The first text box's onchange event handler is connected to the function txtName_onchange(), the second text box's onblur event handler is connected to the function txtAge_onblur(), and the button's onclick event handler is connected to the function butCheckForm_onclick(). These functions are defined in a script block in the head of the page. We will look at each of them in turn, starting with butCheckForm_onclick().
The first thing we do is define a variable, myForm, and set it to reference the Form object created by our <FORM> tag later in the page.
function butCheckForm_onclick() { var myForm = document.form1;
Doing this reduces the size of our code each time we want to use the form1 object. Instead of document.form1 we can just type myForm. It makes our code a bit more readable and therefore easier to debug, and it saves typing. When we set a variable to be equal to an existing object, we don't (in this case) actually create a new form1 object. Instead we just point our variable to the existing form1 object. So when we type myForm.name JavaScript checks our variable, finds it's actually storing the location in memory of the object form1 and uses that object instead. All this goes on behind the scenes so we don't need to worry about it and can just use myForm as if it was document.form1.
Having got our reference to the Form object, we then use it in an if statement to check whether the value in the text box named txtAge or the text box named txtName actually contains any text.
if (myForm.txtAge.value == "" || myForm.txtName.value == "") { alert("Please complete all the form"); if (myForm.txtName.value == "") { myForm.txtName.focus(); } else { myForm.txtAge.focus(); } }
If we do find an incomplete form, we alert the user. Then in an inner if statement we check which text box was not filled in. We set the focus to the offending text box, so that the user can start filling it in straight away without having to move the focus to it themselves. It also lets the user know which text box our program considers needs filling in. To avoid annoying your users, make sure that text in the page tells them which fields are required.
If the original outer if statement found that the form was complete, then it would let the user know with a thank you message.
else { alert("Thanks for completing the form " + myForm.txtName.value); } }
In this sort of situation, it's probably more likely that at this point, having validated the form, we'd submit it to the server for processing. We can do this using the Form object's submit() method as we'll see in the chapters on server-side programming.
The next of our three functions is txtAge_onblur(), which is connected to the onblur event of our txtAge text box. The purpose of this function is to check that the string value the user entered into the age box actually consists of number characters.
function txtAge_onblur() { var txtAge = document.form1.txtAge;
Again at the start of the function we declare a variable and set it to reference an object; this time it's the Text object created for the txtAge text box that we define further down the page. Now instead of having to type document.form1.txtAge every time we just type txtAge and it acts as the same thing. It certainly helps save those typing fingers, especially since it's a big function with multiple use of the txtAge object.
The following if statement checks to see if what has been entered in the txtAge text box can be converted to a number. We use the isNaN() function to do this for us. If the value in txtAge test box is not a number then it's time to tell the user and set the focus back to the offending element with the focus() method of the corresponding Text object. Additionally, this time we also highlight the text by using the Text object's select() method. It makes it even clearer to the user, and they can rectify the problem without needing to delete text first.
if (isNaN(txtAge.value) == true) { alert("Please enter a valid age"); txtAge.focus(); txtAge.select(); } }
We could go further and check that the number inside the text box is actually a valid age, for example -191 is not a valid age, nor is 255 likely to be. We just need to add another if statement to check for these possibilities, but I'll leave that as an extra exercise!
This function is connected to the onblur event handler of the txtAge text box, but why didn't we use the onchange event handler, with the advantage that we only recheck the value when it's actually been changed? The onchange would not fire in the situation where the box was empty before focus was passed to it, and after focus was passed away from it. However, leaving the checking of the form completion until just before the form is submitted is probably better as some users prefer to fill in information out of order and come back to some form elements later.
The final function is for the txtName text box's onchange event. Its use here is a little flippant, and more as an example of the onchange event.
function txtName_onchange() { window.status = "Hi " + document.form1.txtName.value; }
When the onchange event fires, when focus is passed away form the name text box and its contents have changed, we take the value of the txtName box and put it into the window's status bar at the bottom of the window. It simply says Hi yourname. We access the status bar using the window object's status property. Although we could just put:
status = "Hi " + document.form1.txtName.value;
I've actually put window in front of this just to make it clear what we are actually accessing. It would be very easy when reading the code to mistake status for a variable, so in this situation, although strictly unnecessary, putting window in front does make the code easier to read, understand, and therefore debug.
Controlling Data Entry Using Form Fields
Creating 'Encoded' Name & Value Pairs
Passing data from one form to another
Addressing Form Field Validation with Regular Expressions and JavaScript 1.2