Chapter 28. Scripting Text Elements

If buttons are the most common form control, text-based input elements are a close second. There are several types of text elements, making them the best tool for inputting data to submit to your web application. They are:

  • The textbox

  • The password textbox

  • The hidden textbox

  • The Multiline textbox

The differences between the textbox types are minimal. Let's start with the simple textbox.

THE TEXTBOX

You create a textbox with the <input/> element and set its type attribute to the value of text, like this:

<input type="text" name="textBox" />

This HTML creates a textbox named textBox. To access it in a form, you get the element either by its id attribute (which this example does not have), or through the form it belongs to. Assuming this textbox resides in a form called theForm, the following code gets a reference to this textbox:

var txtBox = document.theForm.textBox;

When you create a textbox, you can set its value attribute to contain a text value. The value attribute dictates what appears inside the textbox when the browser renders it. This attribute maps directly to the value property, so you can get or set the text in a textbox by using the value property like this:

txtBox.value = "Some new data";

The contents of the value property are always a string, even if numeric characters are entered. So when you expect a textbox to be used for numeric data, it's always a good idea to convert the textbox's value to a number by using the parseInt() or parseFloat() methods. Not only does the conversion save you from unwanted string concatenation operations (using the + operator), but it also helps you spot invalid data.

In addition to the common properties and methods discussed in Lesson 26, textbox objects have a method called select(); it selects all the text inside the textbox. When used in combination with the focus() method, select() is useful when you want to direct a user to a particular textbox's value, such as when the user enters invalid data.

Also, textbox objects have more events than just the focus and blur events discussed in Lesson 26. They have:

  • change: Fires when the textbox loses focus and only if the text inside the textbox changed.

  • select: Fires when a textbox's text is selected (calling select() fires this event too).

  • keydown: Fires when a key on the keyboard is pressed down.

  • keyup: Fires when a pressed key on the keyboard is released.

  • keypress: Fires when a key on the keyboard is pressed and released.

THE PASSWORD TEXTBOX

The only purpose of the password textbox is to let users type a password while visually obfuscating each character. This obfuscation is only visual, keeping anyone looking over the user's shoulder from seeing the text the user types. The password textbox object's value property contains the actual text without any attempt at obfuscation or encryption of the data. This is actually beneficial, as you can compare the data input in a password textbox with other form data like the data input in a second password textbox, which is common.

To create a password textbox, use an <input/> element and set its type as password, like this:

<input type="password" name="password1" />

Password textboxes have the same methods and events as normal textboxes.

THE HIDDEN TEXTBOX

Like the password textbox, the hidden textbox is a specialty control that was derived for one purpose. Hidden textboxes hold the same type of data that other textboxes can hold, the primary difference being that hidden textboxes are hidden from view. Since they are hidden, the only way to get and set data in a hidden textbox is through the value attribute and property.

Hidden textboxes are created with the <input/> element, like this:

<input type="hidden" name="hiddenTextBox />

Because you use the <input/> element to create this textbox, it has the same properties, methods, and events as the normal and password textboxes. Yes, hidden textboxes even have the keyboard events, but good luck getting them to fire.

THE MULTILINE TEXTBOX

One problem with the normal textbox is that it allows only one line of text. In order to allow the user to input more than one line at a time, you can create a multiline textbox with the <textarea/> element:

<textarea name="multiLine" cols="30" rows="20">
    Line 1
    Line 2
</textarea>

The cols and rows attributes determines the size of the <textarea/> element when rendered by the browser, but CSS can be used to set more exact dimensions. These two attributes are available to you in the DOM, but rarely, if ever, will you want to change them dynamically.

Like the other textboxes, the <textarea/> element object has a value property, and it gets and sets the text between the opening and closing tags of the element. Also like the other textboxes, <textarea/> objects have the select() method, as well as the change, keydown, keyup, and keypress events.

TRY IT

In this lesson, you learn about the various textbox controls. You also learn basic form validation and how to cope with invalid data with the value property and select() and focus() methods.

Lesson Requirements

For this lesson, you need a text editor; any plain text editor will do. For Microsoft Windows users, Notepad is available by default on your system or you can download Microsoft's free Visual Web Developer Express (www.microsoft.com/express/web/) or Web Matrix (www.asp.net/webmatrix/). Mac OS X users can use TextMate, which comes as part of OS X, or download a trial for Coda (www.panic.com/coda/). Linux users can use the built-in VIM.

You also need a modern web browser. Choose any of the following:

  • Internet Explorer 8+

  • Google Chrome

  • Firefox 3.5+

  • Apple Safari 4+

  • Opera 10+

Create a subfolder called Lesson28 in the JS24Hour folder you created in Lesson 1. Store the files you create in this lesson in the Lesson28 folder.

Step-by-Step

  1. Type the following HTML:

    <html>
    <head>
        <title>Lesson 28: Example 01</title>
    </head>
    <body>
    <form name="theForm" action="" onsubmit="validateForm(event)">
        <p>
            Name: <input type="text" name="txtName" />
        </p>
        <p>
            Age: <input type="text" name="txtAge" />
        </p>
        <p>
            Email: <input type="text" name="txtEmail" />
        </p>
        <p>
            Password: <input type="password" name="txtPassword1" />
        </p>
        <p>
            Retype Password: <input type="password" name="txtPassword2" />
        </p>
    
        <input name="btnSubmit" type="submit" value="Submit" />
    </form>
    <script type="text/javascript" src="eventutility.js"></script>
    <script type="text/javascript">
    
    </script>
    </body>
    </html>

    Save this as lesson28_example01.htm. The page consists of one <form/> named theForm. It has an onsubmit event handler set to the validateForm() function. Inside the form are several textboxes with which the user can input his or her name, age, e-mail and password, as well as a submit button.

  2. The first bit of JavaScript you'll write is a function called isEmpty(). It is bold in the following code; add it to your file.

    <html>
    <head>
        <title>Lesson 28: Example 01</title>
    </head>
    <body>
    <form name="theForm" action="" onsubmit="validateForm(event)">
        <p>
            Name: <input type="text" name="txtName" />
    </p>
        <p>
            Age: <input type="text" name="txtAge" />
        </p>
        <p>
            Email: <input type="text" name="txtEmail" />
        </p>
        <p>
            Password: <input type="password" name="txtPassword1" />
        </p>
        <p>
            Retype Password: <input type="password" name="txtPassword2" />
        </p>
    
        <input name="btnSubmit" type="submit" value="Submit" />
    </form>
    <script type="text/javascript" src="eventutility.js"></script>
    <script type="text/javascript">
    function isEmpty(value) {
        return (value === "");
    }
    </script>
    </body>
    </html>

    Its job is simple: Return a Boolean value based on whether the string is empty.

  3. Now start writing the validateForm() function. Add the bold code in this sample:

    <html>
    <head>
        <title>Lesson 28: Example 01</title>
    </head>
    <body>
    <form name="theForm" action="" onsubmit="validateForm(event)">
        <p>
            Name: <input type="text" name="txtName" />
        </p>
        <p>
            Age: <input type="text" name="txtAge" />
        </p>
        <p>
            Email: <input type="text" name="txtEmail" />
        </p>
        <p>
            Password: <input type="password" name="txtPassword1" />
        </p>
        <p>
            Retype Password: <input type="password" name="txtPassword2" />
        </p>
    
        <input name="btnSubmit" type="submit" value="Submit" />
    </form>
    <script type="text/javascript" src="eventutility.js"></script>
    <script type="text/javascript">
    function isEmpty(value) {
        return (value === "");
    }
    function validateForm(event) {
        var theForm = document.theForm;
        var txtName = theForm.txtName;
        var txtAge = theForm.txtAge;
        var txtEmail = theForm.txtEmail;
        var txtPassword1 = theForm.txtPassword1;
        var txtPassword2 = theForm.txtPassword2;
        var button = theForm.btnSubmit;
        var age = parseInt(txtAge.value);
    
        button.disabled = true;
    }
    </script>
    </body>
    </html>

    This is the beginning of the function. It defines a variety of variables, the majority of which get the DOM object of each control in the form. The value of the txtAge textbox is converted to a number, which is assigned to the final variable, age.

  4. Now begin to validate the textboxes in the order in which they appear. Add the bold code:

    <html>
    <head>
        <title>Lesson 28: Example 01</title>
    </head>
    <body>
    <form name="theForm" action="" onsubmit="validateForm(event)">
        <p>
            Name: <input type="text" name="txtName" />
        </p>
        <p>
            Age: <input type="text" name="txtAge" />
        </p>
        <p>
            Email: <input type="text" name="txtEmail" />
        </p>
        <p>
            Password: <input type="password" name="txtPassword1" />
        </p>
        <p>
            Retype Password: <input type="password" name="txtPassword2" />
        </p>
    
        <input name="btnSubmit" type="submit" value="Submit" />
    </form>
    <script type="text/javascript" src="eventutility.js"></script>
    <script type="text/javascript">
    function isEmpty(value) {
        return (value === "");
    }
    
    function validateForm(event) {
        var theForm = document.theForm;
        var txtName = theForm.txtName;
        var txtAge = theForm.txtAge;
        var txtEmail = theForm.txtEmail;
        var txtPassword1 = theForm.txtPassword1;
        var txtPassword2 = theForm.txtPassword2;
        var button = theForm.btnSubmit;
        var age = parseInt(txtAge.value);
    
        button.disabled = true;
        // validate name field
        if (!isEmpty(txtName.value)) {
    
            // more code here
    
        } else {
            alert("Please enter your name.");
            txtName.focus();
        }
    
        button.disabled = false;
        eventUtility.preventDefault(event);
    }
    </script>
    </body>
    </html>

    This is the basic pattern used to validate all the textboxes. The idea is to ensure that as one textbox passes validation, the validation of the next one begins in the if block of the previous textbox's validation check. Once the final validation check is performed and the check passes, the function simply returns and the browser submits the form.

    If any textbox fails validation, its else block sends a message to the user and gives focus to the textbox. Then the button is re-enabled and the form is prevented from being submitted.

    It's a quick and easy way to validate a form.

  5. Add the code to validate the age textbox. Use the isNaN() method to determine if what the user entered was a number. Also check to make sure the number entered is greater than zero. That code is bold here:

    function validateForm(event) {
        var theForm = document.theForm;
        var txtName = theForm.txtName;
        var txtAge = theForm.txtAge;
        var txtEmail = theForm.txtEmail;
        var txtPassword1 = theForm.txtPassword1;
        var txtPassword2 = theForm.txtPassword2;
        var button = theForm.btnSubmit;
        var age = parseInt(txtAge.value);
    button.disabled = true;
    
        // validate name field
        if (!isEmpty(txtName.value)) {
            // validate age
            if (!isNaN(age) && age > 0) {
    
               // more code here
    
            } else {
                alert("Please enter your age.");
                txtAge.focus();
                txtAge.select();
            }
    
        } else {
            alert("Please enter your name.");
            txtName.focus();
        }
    
        button.disabled = false;
        eventUtility.preventDefault(event);
    }

    For printing, the HTML and isEmpty() function were omitted. This code adds the age validation, and it looks similar to the code that validates the name textbox.

  6. Now add code to validate the e-mail address. Ensure that the @ symbol is present in the textbox's value, and that it isn't the first character in the string. That code is bold here:

    function validateForm(event) {
        var theForm = document.theForm;
        var txtName = theForm.txtName;
        var txtAge = theForm.txtAge;
        var txtEmail = theForm.txtEmail;
        var txtPassword1 = theForm.txtPassword1;
        var txtPassword2 = theForm.txtPassword2;
        var button = theForm.btnSubmit;
        var age = parseInt(txtAge.value);
    
        button.disabled = true;
    
        // validate name field
        if (!isEmpty(txtName.value)) {
    
            // validate age
            if (!isNaN(age) && age > 0) {
    
                // validate email field
                if (txtEmail.value.indexOf("@") > 0) {
    
                    // more code here
    
                } else {
    alert("Please enter a valid email address.");
                    txtEmail.focus();
                    txtEmail.select();
                }
    
            } else {
                alert("Please enter your age.");
                txtAge.focus();
                txtAge.select();
            }
    
        } else {
            alert("Please enter your name.");
            txtName.focus();
        }
    
        button.disabled = false;
        eventUtility.preventDefault(event);
    }

    The same thing as before happens if the validation test fails. An alert box asks the user to enter a valid e-mail address, and focus is given to the textbox.

  7. Now add the code to validate the passwords. This is a two-step process: Make sure that one of the password fields isn't empty, and then make sure both fields have the same text. Add the bold code:

    function validateForm(event) {
        var theForm = document.theForm;
        var txtName = theForm.txtName;
        var txtAge = theForm.txtAge;
        var txtEmail = theForm.txtEmail;
        var txtPassword1 = theForm.txtPassword1;
        var txtPassword2 = theForm.txtPassword2;
        var button = theForm.btnSubmit;
        var age = parseInt(txtAge.value);
    
        button.disabled = true;
    
        // validate name field
        if (!isEmpty(txtName.value)) {
    
            // validate age
            if (!isNaN(age) && age > 0) {
    
                // validate email field
                if (txtEmail.value.indexOf("@") > 0) {
    
                    // validate password - pass 1
                    if (!isEmpty(txtPassword1.value)) {
    
                        // validate password - pass 2
                        if (txtPassword1.value === txtPassword2.value) {
                            return;
    } else {
                            alert("Passwords do not match. Please reenter them.");
                            txtPassword1.focus();
                            txtPassword1.select();
                        }
    
                    } else {
                        alert("Password cannot be blank.");
                        txtPassword1.focus();
                        txtPassword1.select();
                    }
    
                } else {
                    alert("Please enter a valid email address.");
                    txtEmail.focus();
                    txtEmail.select();
                }
    
            } else {
                alert("Please enter your age.");
                txtAge.focus();
                txtAge.select();
            }
    
        } else {
            alert("Please enter your name.");
            txtName.focus();
        }
    
        button.disabled = false;
        eventUtility.preventDefault(event);
    }

    It doesn't matter which password field you check to see if it's empty. This code checks the first password field. If that check passes, the values of both password textboxes are compared. If all validation rules are passed, the function returns and the browser submits the form. If not, an alert box tells the user what he or she needs to do in order to enter valid information, and the browser is prohibited from submitting the form.

To get the sample code files, you can download Lesson 28 from the book's website at www.wrox.com.

Note

Please select Lesson 28 on the DVD to view the video that accompanies this lesson.

Step-by-Step
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.82.217