Universal Class: Over 500 Online Certificate Courses
 
 
How to Script Forms with JavaScript
 
 

How to Script Forms with JavaScript

 

HTML forms are the objects used to take template information from a user. For instance, if you work with customers, you need a customer's first and last name, address, and zip code. A form object displays input fields for the user to enter this information and send it back to your web server. You can use JavaScript to provide dynamic customizations to a standard HTML form. This lesson explains some ways that JavaScript is useful when using forms in your web pages and how to handle events and validations before submitting the form data back to your server-side scripts. 

What is a Form?

An HTML form is any text box, check box, or radio button that takes input from a user. HTML comes with several form input types that you can use without creating your own input options. You can customize7 these form elements using CSS, JavaScript or inline HTML tag properties. 

Most webmasters need some customizations to their forms, and this is where JavaScript comes in handy. JavaScript lets you perform client-side dynamic calls to forms and the input typed by your users. For instance, suppose you want to ensure that the user has entered a value into a "first_name" text box before you send the input to the server. You could send the input to the server, process the data, find the missing input variable, and then send the form back to the user with an error message. This process takes time, so you can do a quick check for an empty first name text box using JavaScript. This is just one of the many reasons for using JavaScript validation in your HTML forms. 

Using JavaScript with Forms

Let's take a simple form that asks the user to input a first and last name. Take a look at the code below.

<!DOCTYPE html>
<html>

<head>

</head>

<body >

   <form action="process_form.php">
      First name:<br>
      <input type="text" id="first_name">
      <br>
      Last name:<br>
      <input type="text" id="last_name"">
      <br><br>
      <input type="submit" value="Submit">
   </form>

</body>
</html>

The above code has one form that displays an input text box for the user's first name and last name. The first input box is "first_name," and we want to ensure that the user enters a value before we send the form to the server processing page named "process_form.php." We can do this with JavaScript. Again, we use the getElementById method to get the form input text box and evaluate if the user entered a value. The input can be any value, but there must be at least one character input. We want to trigger the JavaScript check when the user clicks the submit button. Your first thought might be to fire the event when the "onclick" event happens. However, HTML forms have their own event trigger when the user clicks the submit button to send form values to the server. This event is called the "onsubmit" trigger. 

Let's add the "onsubmit" event handler and hook into the current HTML page. Below is a complete copy of our user input form page. 

<!DOCTYPE html>
<html>

<head>

<script>

function ValidateFirstName ( )
{
    var firstName = document.getElementById("first_name");

    if (firstName.value == "")

    {

       return false;

    }

    else

    {

       return true;

    }
}

</script>

</head>

<body >

   <form action="process_form.php" onsubmit="return ValidateFirstName();">
      First name:<br>
      <input type="text" id="first_name">
      <br>
      Last name:<br>
      <input type="text" id="last_name"">
      <br><br>
      <input type="submit" value="Submit">
   </form>

</body>
</html>

Notice we added an "onsubmit" event trigger that points to the JavaScript function "ValidateFirstName()" we've defined in the HTML script tag. Notice that we added a "return" keyword in front of the trigger. The "return" statement sets the onsubmit function to true or false. If the boolean value "false" is returned by the function, it tells the form to stop submitting and the page will not send data to the server. The boolean value false tells the HTML form that the user's input has failed the validation check. Conversely, if the form validation function returns the boolean value of true, the HTML event knows that it can continue with submission of the user input.

In the JavaScript function, we get the "first_name" HTML element, identify if there is input and return true or false depending on the input. If the value is equal to a blank string, then we know that the user entered no value. Otherwise, the user entered a value and we can continue with the form processing. You can also perform this type of validation with other form elements. Usually, any required fields are marked for your users, so they know that they need to enter a value in specific fields. For instance, the address input box might be required, but you have a second address input box for apartments or suite numbers. You'd put an asterisk next to the first address field but not the second. Or, you can just put a label named "required" next to the field. However you decide to mark the HTML form elements, just make sure they are easily identified by users to avoid confusion.

How to Dynamically Add and Delete Form Items

We've just seen how to use form input text boxes and validation through JavaScript, but forms usually have other types of input such as radio buttons and check boxes. You can dynamically add and delete any form element within your script. This is typically done when you want to take additional information from a user after they enter other input. For instance, suppose once a user chooses "Yes" in a radio button group, you then display check boxes for additional information. This can be done using JavaScript functions and the "createElement" method.

Interested in learning more? Why not take an online class in JavaScript?

Let's change our form to display two radio buttons that display check boxes when the user chooses "Yes."

<!DOCTYPE html>
<html>

<head>

<script>

function ValidateFirstName ( )
{
    var firstName = document.getElementById("first_name");

    if (firstName.value == "")

    {

       return false;

    }

    else

    {

       return true;

    }
}

function addCheckboxes ()
{

 var radio = document.getElementById("iLikeJs");

 if (radio.checked)

 {

    document.getElementById("moreCheckboxes").innerHTML = "<input type='checkbox' name='why' value='because' />"; 

 }

 else

 {

     document.getElementById("moreCheckboxes").innerHTML = "";

 }

 
}

</script>

</head>

<body >

   <form action="process_form.php" onsubmit="return ValidateFirstName();">
      First name:<br>
      <input type="text" id="first_name">
      <br>
      Last name:<br>
      <input type="text" id="last_name""> <br>

      Do you like JavaScript?<br>
      <input type="radio" id="iLikeJs" name="likeJavascript" value="yes" onclick="addCheckboxes()">

      <input type="radio" name="likeJavascript" value="no" onclick="addCheckboxes()"><br>
      <div id="moreCheckboxes"> </div>
      <br><br>
      <input type="submit" value="Submit">
   </form>

</body>
</html>

We've added some functionality to our form and JavaScript functions. First, we added a radio button. Notice that we used the "name" property and both radio buttons have the same name. While each element must have a unique id property, they can have the same name. Radio buttons and check boxes often have the same name to group them together. When one radio button is checked, any currently checked boxes are unchecked. This means that the user can only have one radio box selected. Check boxes are used for multiple optional values. 

The JavaScript function only triggers if the "Yes" radio button is clicked. The function checks that the radio button returns "true" for checked, and if so adds a check box to the div with the id "moreCheckboxes." In this example, we add the actual HTML for the check box, and we only add one check box to the div. If the user decides to change the answer to "No," the check box is removed from the div. Notice that we added an id property to the radio button that uses the "Yes" answer. The radio button with the id of "iLikeJs" is retrieved in the JavaScript function and the "checked" property is determined. This value returns true or false, and it's a natural property included with the HTML form element object definition. 

The above code is an example of dynamically working with forms, and adding and removing elements as you receive user input. 

Dynamically Working with Select Boxes

We talked about dynamically working with elements as you receive user input, and one common form element used with JavaScript and dynamic loading is the select box. The select box is the drop-down element that displays a number of values. From the list, the user can choose one option. What if you have hundreds of options, but you only want to show a few options to the user based on some kind of input. This is common when you have too many drop-down values to display to the user, so it could be too frustrating for the user to find a specific element. For instance, you wouldn't show states with a list of countries. But, you can dynamically fill a list of states based on the country the user chooses from another select box. This section will show you how to fill a select box after a user sends input from a radio box.

<!DOCTYPE html>
<html>

<head>

<script>

function ValidateFirstName ( )
{
    var firstName = document.getElementById("first_name");

    if (firstName.value == "")

    {

       return false;

    }

    else

    {

       return true;

    }
}

function addOptions ()
{

 document.getElementById("selectBoxOptions").options.length = 0;

 if (radio.checked)

 {

    var option1 = document.createElement("option");

    var option2 = document.createElement("option");

    option1.text = "Because I like it.";

    option1.value = "because";

    option2.text = "Because it is dynamic.";

    option2.value = "dynamic";

    document.getElementById("selectBoxOptions").add(option1);

    document.getElementById("selectBoxOptions").add(option2);

 }

 
}

</script>

</head>

<body >

   <form action="process_form.php" onsubmit="return ValidateFirstName();">
      First name:<br>
      <input type="text" id="first_name">
      <br>
      Last name:<br>
      <input type="text" id="last_name""> <br>

      Do you like JavaScript?<br>
      <input type="radio" id="iLikeJs" name="likeJavascript" value="yes" onclick="addOptions()">

      <input type="radio" name="likeJavascript" value="no" onclick="addOptions()"><br>
      <select id="selectBoxOptions"> </select>
      <br><br>
      <input type="submit" value="Submit">
   </form>

</body>
</html>

In this example, we're using the same logic except instead of check boxes, we gave the user a list of options from a select box. When the user clicks the "Yes" radio button, a list of options is populated in the select box drop-down named "selectBoxOptions." 

There's more logic to this page than the others. First, we use the same function except we clear the select box options each time. The reason we clear the text box is because the append function keeps adding more options to the drop-down instead of clearing the current list and replacing with a new list. This is important when you work with dynamic select boxes. By setting the option length to zero, the element no longer has any elements listed. However, if the "Yes" radio button is selected, two options are shown to the user. The first one is "Because I like it" and the other is "Because it is dynamic." Notice that the text and values are different. The value is what you store in a database or use for form processing while the text is just displayed to the user. 

This lesson covered several concepts in JavaScript and forms. HTML forms can be several elements long with several options when you dynamically create and remove elements. The JavaScript function can be hundreds of lines of code. However, it's best to start practicing with a handful of form elements, write some JavaScript code and expand your logic later. This will eliminate logic bugs and help you practice with form dynamics before diving into more complex functionality.

 
 
Popular Courses
 
Learn More! Take an Online Course...