CommonLounge Archive

HTML forms and JavaScript

September 26, 2018

HTML Forms are used everywhere on web - for creating an account, for submitting applications, for submitting payment information, etc. In this tutorial you will learn how to read HTML form data from JavaScript and how to perform form validation (that the user has filled the form as expected).

Note: Once the form has been filled satisfactorily by the user and submitted, often the information is sent to server (the computer which responds to user requests for your website) or stored in your database. For example, if the user just entered his log-in details, this data is sent to the server, which responds back saying whether the log-in credentials were correct or not. We’ll cover such interactions (making web-requests from JavaScript) later in the course.

HTML Forms

An HTML form is defined by the <form> and </form> tags. Open up your code editor and make a new file called forms.html:

<html>
    <head>
        <title>Using JavaScript with forms</title>
    </head>
    <body>
        <form name="form1">
        </form>
    </body>
</html>

This is an empty form, which has the name attribute set to "form1".


From JavaScript, there are many ways to get a reference to the <form> element. Here are some:

document.form1;           // document.form-name
document.forms[0];        // 0 for 1st form, 1 for 2nd form and so on.
document.forms["form1"];  // document.forms["form-name"]
// there can be multiple HTML elements with the same name
// hence "getElementsByName" returns an array
// to get our form, we need to get the first element of the array
document.getElementsByName("form1")[0] 

All of these refer to the same <form> element.

Form elements and Submit button

Inside the <form> tag, we can add form elements like text field, checkbox, etc. A form also generally has a submit button which is used to submit the data once the user has filled the form.

Form elements are specified by using the <input> tag. Every form element must have a name attribute. If an element doesn’t have a name attribute, its data is not sent. Moreover, the names must be unique. The type attribute is used to specify the type of the input field. For example, text means a text field, radio is for multiple choice fields, checkbox is for checkboxes, etc.

Let’s create a simple form.

<html>
    <head>
        <title>HTML Forms</title>
    </head>
    <body>
        <form name="form1">
            Name: 
            <input type="text" name="nameinput" placeholder="Enter your name.."> <br> <br>
            E-mail:
            <input type="email" name="emailinput" placeholder="Enter your email.."> <br> <br>
            Do you like Commonlounge?
            <input type="radio" name="likecommonlounge" value="Yes">Yes
            <input type="radio" name="likecommonlounge" value="Definitely Yes">Definitely Yes <br> <br>
            <input type="checkbox" name="tandc"> I accept the terms and conditions <br> <br>
            <input type="submit">
        </form>
        <p id="formentries">
            <!-- Ignore this paragraph for now. We'll use it soon. -->
        </p>
    </body>
</html>

Note: Each input field has a unique name except for the radio type. All the options for one question have the same name.

Your form should look something like this:

To learn more about HTML forms, see Building Interactive Forms tutorial from the Learn HTML & CSS course.


We can access the form elements in JavaScript using their names:

document.form1.nameinput;
document.form1.likecommonlounge;
document.form1.tandc;

Tip: Again, it’s a good idea to open the console and play around with this. Because console has autocomplete, it is quite helpful in exploring what you get when you type in the above.

And we can also access the values for each form element. For example:

f.nameinput.value;        // text typed by the user
f.likecommonlounge.value; // "value" attribute of the selected radio button
f.tandc.checked;          // true if checkbox is checked, false otherwise

Printing form values

Now that we have a simple HTML

with some elements, and we know how to access the form elements from JavaScript, let’s write a function to print the values entered in the form. Then, we’ll connect this function to be called when the form is submitted.

Exercise: You have already learnt everything required to write this function yourself. So if you want to, you can try writing the function on your own and calling it manually from the console to see if its works.

Okay, so let’s see what the function looks like:

<script>
    function printValues() {
        var f = document.form1;
        // Construct finalstring
        var finalstring = "<br>";
        finalstring += "Name = " + f.nameinput.value + "<br>";
        finalstring += "Email = " + f.emailinput.value + "<br>";
        finalstring += "Do you like commonlounge? ";
        finalstring += f.likecommonlounge.value + "<br>";
        finalstring += "T and C accepted? ";
        finalstring += f.tandc.checked + "<br><br>";
        // Change paragraph <p id="formentries">
        var p = document.getElementById("formentries");
        p.innerHTML = finalstring;
        return false;
    }
</script>

Most of the code above should be clear to you from reading it. We just go through each form element, and keep constructing the finalstring. Finally, we update the innerHTML of <p id="formentries">.

However, there are a couple of notes

  1. Make sure to write the above code after the </form> closing tag. This is because we can access an element using the document object only after it has been created.
  2. We return false because we don’t want the form to actually submit. This function will be called from the form’s onsubmit event attribute which is called when submit button is clicked. If the value received from the function called is false then the form doesn’t submit. This way we can prevent the form from submitting. Change your form’s definition to this:
<form name="form1" onsubmit="return printValues()">

Your HTML file should now look like this:

<html>
    <head>
        <title>HTML Forms</title>
    </head>
    <body>
        <form name="form1" onsubmit="return printValues()">
            Name: 
            <input type="text" name="nameinput" placeholder="Enter your name.."> <br> <br>
            E-mail:
            <input type="email" name="emailinput" placeholder="Enter your email.."> <br> <br>
            Do you like Commonlounge?
            <input type="radio" name="likecommonlounge" value="Yes">Yes
            <input type="radio" name="likecommonlounge" value="Definitely Yes">Definitely Yes <br> <br>
            <input type="checkbox" name="tandc"> I accept the terms and conditions <br> <br>
            <input type="submit">
        </form>
        <p id="formentries">
        </p>
        <script>
            function printValues() {
                var p = document.getElementById("formentries");
                var f = document.form1;
                var finalstring = "<br>";
                finalstring += "Name = " + f.nameinput.value + "<br>";
                finalstring += "Email = " + f.emailinput.value + "<br>";
                finalstring += "Do you like commonlounge? ";
                finalstring += f.likecommonlounge.value + "<br>";
                finalstring += "T and C accepted? ";
                finalstring += f.tandc.checked + "<br><br>";
                p.innerHTML = finalstring;
                return false;
            }
        </script>
    </body>
</html>

Try filling in the form, and clicking submit. You’ll see the values you filled show up below the form.

Pretty cool, right?

Form validation

You must have come across alert boxes in red colour with messages similar to “Password must contain at-least one number”. These messages are part of a process called form validation. Form validation, as the name suggests, is the process where we check that the data submitted by a user is valid. That is, we have a set of rules that the input must satisfy, and we check whether all of those conditions are true.

Generally, form values are validated twice — once on the user’s machine (client side) and once on the computer hosting the website (server side). This is to ensure the validity of data even if JavaScript is disabled on the client’s browser or the user does malicious things such as change the JavaScript validation function before submitting (yes, that is possible!).

The overall flow for form validation will be:

  • Get user inputs from different form elements.
  • Check each input value against some rules, and return an array of error messages (strings) if any of the rules is violated.
  • If there is no error message, show an alert box and submit the form.

The form

Let us create a new form:

<html>
    <head>
        <title>JavaScript: HTML forms</title>
    </head>
    <form name="form1">
        Name: <br>
        <input type="text" name="nameinput" placeholder="Enter your name">
        <br><br>
        Email: <br>
        <input type="email" name="email" placeholder="Enter your email">
        <br><br>
        Password (should contain both lowercase and uppercase characters): <br>
        <input type="password" name="password">
        <br><br>
        Age (should be between 13 and 50): <br>
        <input type="text" name="age">
        <br><br>
        <input type="checkbox" name="tandc"> I accept the terms and conditions
        <br><br>
        <input type="submit">
        <br><br>
    </form>
    <p id="errors" style="color: red;">
    </p>
</html>

Notice the type = "password" for the password field, and the empty paragraph for errors <p id="errors">, with style="color: red;" (so that all text inside this paragraph will be displayed in red color).

This is what the form looks like:

The rules

Here’s the list of rules we would like the form inputs to satisfy:

  • None of the fields should be empty
  • Name
  • Maximum length = 50 characters.
  • Email
  • Since the type="email", HTML already performs some basic checks on this form element. In particular, HTML ensures that the string is of the form xx@zz. We won’t do any additional checks.
  • Password
  • Minimum length = 6 characters.
  • Maximum length = 20 characters.
  • At least one alphabet and one number should be present
  • Age
  • Value should be between 13 and 100
  • Terms and Conditions
  • Should be checked before submission

Validation (the code)

Now that we have the set of rules to be checked, let’s write the JavaScript code.

Exercise: Again, you have already learnt everything required to write this function yourself. So if you want to, you can try writing the function on your own.

First, let’s write a function to validate the password.

function validatePassword(password) {
    // Initialization
    var len = password.length;
    var errors = [];
    var alpha_count = 0;
    var digit_count = 0;
    // Check not empty
    if (password === "") {
        errors.push("Password field is empty");
        return errors; // if password is empty return immediately
    }
    // Check length
    if (len <= 6 || len >= 20)
        errors.push("Password must be between 6 and 20 characters in length");
    // Check at-least one alphabet and at-least one number
    for (var i = 0; i < len; i++) {
        if (password[i] >= 'a' && password[i] <= 'z')
            alpha_count++;
        if (password[i] >= 'A' && password[i] <= 'Z')
            alpha_count++;
        if (password[i] >= '0' && password[i] <= '9')
            digit_count++;
    }
    if (!(alpha_count > 0 && digit_count > 0))
        errors.push("Password must have at-least one alphabet and at-least one number");
    return errors;
}

The most important parts of the code are as follows:

  1. We start with an empty array error, and push error strings if we encounter any violations.
  2. If the password is empty, then we push an error message to the errors array and return immediately.
  3. Then, we check that the length constraints are satisfied.
  4. Checking that the password has at-least one alphabet and at-least one number is done with the help of a for-loop above.
  5. Checking is a character is a lowercase alphabet is done using (password[i] >= 'a' && password[i] <= 'z'). Similarly, we check for uppercase alphabets and digits.

We can make similar functions for name, age and checkbox as well. We will also write a validator for email but it will only check if it is empty or not.

function validateName(name) {
    var errors = [];
    if (name === "") {
        errors.push("Name field is empty");
        return errors; // if name is empty return immediately
    }
    if (name.length > 50)
        errors.push("Name should be at most 50 characters in length");
    return errors;
}
function validateEmail(email) {
    if (email === "")
        return ["Email field is empty"];
    return [];
}
function validateAge(age) {
    var ageint = parseInt(age);
    var errors = [];
    if (age === "") {
        errors.push("Age field is empty");
        return errors; // if age field is empty return immediately
    }
    if (isNaN(age)) {
        errors.push("Please enter a numerical value");
        return errors;
    }
    if (ageint < 13 || ageint > 100)
        errors.push("Age should be between 13 and 100");
    return errors;
}
function validateTC(checkbox) {
    var errors = [];
    if (!checkbox.checked)
        errors.push("You must agree to the terms and conditions.");
    return errors;
}

We have used isNaN() function in validateAge() to check if the entered value in the age field is not a number. Rest of the code is fairly straightforward.


Now let’s create the final validator function:

function validateSubmission() {
    // Get reference to errors paragraph and form 
    var p = document.getElementById("errors");
    var f = document.form1;
    // Get values of all the fields
    var name = f.nameinput.value;
    var email = f.email.value;
    var password = f.password.value;
    var age = f.age.value;
    var tc = f.tandc;
    // Validate each field and concatenate all the errors into one array
    var listOfErrors = [];
    listOfErrors = listOfErrors.concat(validateName(name),
                                       validateEmail(email),
                                       validatePassword(password),
                                       validateAge(age),
                                       validateTC(tc));
    // If at-least one error, display the errors and don't submit.
    if (listOfErrors.length > 0) {
        // At-least one error
        var errorString = "Errors: <br>";
        for (var i = 0; i < listOfErrors.length; i++) {
            errorString += listOfErrors[i] + "<br>";
        }
        p.innerHTML = errorString;
        return false; // don't submit the form
    }
    // Validation is done and everything is fine. Submit the form. 
    p.innerHTML = ""; // remove any previously displayed errors
    alert("Validation is done! Everything is fine!");
    return true; // submit!
}

Here, we use the .concat() function to concatenate arrays. Rest of the code is pretty straight forward.

If the validation happens smoothly we create an alert box with the message “Validation is done! Everything is fine!“.


Finally we need update the <form> definition by adding the onsubmit attribute.

<form name="form1" onsubmit="return validateSubmission()">

Go ahead and open this page in a browser. You should see errors (if any) when you submit incorrect data. For example:

Summary

In this tutorial, you learnt how to

  • Create HTML forms and form elements using the <form> and <input> tags respectively.
  • Get access to form input fields and values from JavaScript using the name attribute.
  • Trigger a JavaScript function call when a form is submitted, and
  • Validate forms using JavaScript, i.e. check whether the values entered by the user satisfy the expected constraints.

Quiz time!


© 2016-2022. All rights reserved.