Broad Network


Same Page Form Feedback with JavaScript

Professional Approach

Forward: You might have come across web page forms were if the user makes a mistake in filling the form the error message would be displayed (usually in red) just above the particular form control (field). Read article for details.

By: Chrysanthus Date Published: 14 Nov 2012

Introduction

You might have come across web page forms were if the user makes a mistake in filling the form the error message would be displayed (usually in red) just above the particular form control (field). I show you how to do that with JavaScript in this article.

You need basic knowledge in HTML (or XHTML) and JavaScript in order to understand this article. If you do not have basic knowledge in HTML then read the series I wrote whose first part is titled, “Getting Started with XHTML”. To arrive at the series, type the title and my name Chrys in the Search Box of this page and click Search. If you do not have basic knowledge in JavaScript then read the series I wrote whose first part is titled, “Getting Started with JavaScript”. To arrive at the series, type the title and my name Chrys in the Search Box of this page and click Search.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Example HTML Form
We shall use the following HTML form for illustration:

<html>
<head>
</head>
<body>
    <form method="post" action="myScript.exe" onsubmit = "return validate()">
                                                                 <br />
        Name: <input type="text" id="Name" name="Name"><br />
                                                                 <br />
        Email: <input type="text" id="Email" name="Email"><br />
                                                                    <br />
        Message: <textarea cols="50" rows="3" id=="Message"></ name="Message"></textarea><br /><br />
        <button type="submit">Send</button>
    </form>
</body>
</html>

In the form the method is POST and the action attribute has the name of the server script file, myScript.exe. This server script files, and the HTML file for the form, can be in the same directory at the server.

The start form tag has the JavaScript onsubmit event. The value of the attribute is, "return validate()". When the submit button is clicked, this attribute calls the JavaScript function, validate(). If all the controls of the form are properly filled, then the function will return Boolean true. If they are not properly filled, then the function will return Boolean false. If true is returned as the value to onsubmit, then the form is submitted; if false is returned the form is not submitted.

Alert Box Validation of HTML Form
Let us see how you would report error using the alert box: The JavaScript validate() function in this article is simple, for pedagogic reasons. It checks the fields one-by-one to see if each field is empty. If any field is empty, the execution of the function is stopped and false is returned. If all the fields are not empty, then true will be returned just as the function is ending. The if-else-if-else construct is used. If a field is empty, before false is returned, JavaScript alert box displays the error message. This is the function:

<script type="text/javascript">

    function validate()
        {
            if (document.getElementById('Name').value == "")
                {
                    alert('The First Name field cannot be empty.');
                    return false;
                }
            else if (document.getElementById('Email').value == "")
                {
                    alert('The Email field cannot be empty.');
                    return false;
                }
            else if (document.getElementById('Message').value == "")
                {
                    alert('The Message field cannot be empty.');
                    return false;
                }
            else
                return true;
        }

</script>

This function shows a normal way of validating with JavaScript, where the alert box is used.

Converting to Same Page Feedback
With Same Page Feedback, there is no alert box. The error message is displayed just above the field control. In order to achieve this, you should have a free space just above each control. This is achieved in the HTML form above with <br /> elements.

You just have to fit the error message in front of the line break element just above the control. How do you do this? In front the line break element in the HTML form, you will have an HTML SPAN element (not shown above). The SPAN element will have an ID attribute and a style attribute for visibility. The SPAN element will always have the error message corresponding to its control just below it.

By default, you make the value of the style visibility property, hidden. This means the SPAN element is normally not visible. When an error is detected in the corresponding control as the submit button is clicked, the SPAN element is made visible. To turn the visibility on and off, the SPAN element should have an ID. JavaScript will use the ID to turn it on and off (see below).

There is one SPAN element for every control that can produce an error. This is what you would normally do. For complex error checking, you can have more than one SPAN element, in which case you would use the display property instead of the visibility property. Alternatively, you can be using JavaScript to change the error message in a particular SPAN element. Well, in this tutorial, we have one SPAN element per control and one error message in each SPAN element.

I assume in this tutorial that when the form is sent successfully to the server, another web page from the server will be returned to the browser to confirm that the form has been sent successfully.

Modified HTML Form
The modified HTML Form to take into account the SPAN elements, is:

<html>
<head>
</head>
<body>
    <form method="post" action="myScript.exe" onsubmit = "return validate()">
        <span id="nameSp" style="visibility:hidden;color:red">The name field cannot be empty!</span><br />
        Name: <input type="text" name="Name"><br />
        <span id="emailSp" style="visibility:hidden;color:red">The Email field cannot be empty!</span><br />
        Email: <input type="text" name="Email"><br />
        <span id="msgSp" style="visibility:hidden;color:red">The Message field cannot be empty!</span><br />
        Message: <textarea cols="50" rows="3" name="Message"></textarea><br /><br />
        <button type="submit">Send</button>
    </form>
</body>
</html>

Note how the SPAN elements have been fitted in front of the line break elements that created blank lines.

The Modified JavaScript Function
The JavaScript function, validate(), has to be modified as well. Instead of displaying the alert box with a pre-typed message for a particular control, it will make the SPAN element with the same pre-typed message above the control, visible. It does this when the user types the content of the control wrongly and clicks the submit button; precisely when the user does not type anything in the control (when the control is empty). This is the modified validate() function:

<script type="text/javascript">

    function validate()
        {
            if (document.getElementById('Name').value == "")
                {
                    document.getElementById('nameSp').style.visibility="visible";
                    return false;
                }
            else if (document.getElementById('Email').value == "")
                {
                    document.getElementById('emailSp').style.visibility="visible";
                    return false;
                }
            else if (document.getElementById('Message').value == "")
                {
                    document.getElementById('msgSp').style.visibility="visible";
                    return false;
                }
            else
                return true;
        }

</script>

Note how the ID’s of the SPAN elements have been used.

You can download the complete code in zip format from,

http://www.broad-network.com/ChrysanthusForcha/Same-Page-Form-Feedback-with-JavaScript.zip

At the server, the script that receives the data set (form information) may be a PHP or Perl script (or some other script language). I assume for this article that you understand such Perl or PHP scripts. If you do not understand such scripts, just search this blog.

This is the third article I am writing on Same Page Form Feedback. I once wrote one for PHP and another for Perl (ActivePerl). This one is for JavaScript. With PHP and Perl, the form data set has to be sent to the server, first. The error will be determined in the server by PHP or Perl, before the error message is sent back to the user (client). With slow lines, this would take time. Same page feedback with JavaScript is faster especially if you have a slow Internet line, because the distance from your client computer to server and back does not have to be traveled, before the error is determined.

That is it. I have given you the basis. You can add your own features. You can go as far as adding custom sound, which will indicate to the user that an error message has just been displayed. When the error message is displayed as explained above, some users may not know that an error message has just been displayed In that case, it is good to have sound. Writing code to produce sound in respond to an event is not obvious. If you want me to address the issue of Sound Responding to Web Page Events with JavaScript, tell me by leaving a comment at the end of this article; leave a comment even if someone else has left the same comment; I would like to know the number of people who are interested.

Chrys

Related Links

Same Page Form Feedback with PHP
Same Page Form Feedback with JavaScript
Same Page Form Feedback with Active Perl
Major in Website Design
Web Development Course

Comments

Become the Writer's Fan
Send the Writer a Message