How To Display Form Fields Based On Selection With Or Without jQuery Cookie

Over these years, adding JavaScript to a form has become very common. The introduction of JavaScript has changed the way in which a user interacts with an online form. It will no longer be just a normal static form for a user to fill in as the whole interaction becomes more responsive. Instant feedback could also be achieved when a user enters invalid information for certain field or according to a certain criteria that the user input, the form will show or hide additional fields.

jQuery Cookie

In fact, most of the people do not like filling up long forms, even if you include fields that are optional, the form can still be overwhelming. In order to enhance the user experience, we can add in JavaScript to hide away fields that are not necessary for normal users. If under certain condition, the user will then need to fill up the additional fields.

Let me show you an example on how to display additional fields based on selected radio button option below.

jQuery Slide Up/Down Form Section Base On Select Radio Button Option

Let's create a simple HTML Markup for the form.

//Example 1: Display Fields Based On Selected Radio Button
<fieldset>
<ol class="formset">
        <li><label for="fname1">First Name: </label>
	<input type="text" id="fname1" value="" name="fname1"/></li>

        <li><label for="lname1">Last Name: </label>
	<input type="text" id="lname1" value="" name="lname1"/></li>

        <li><label for="email1">Email Address: </label><br />
	<input type="text" id="email1" value="" name="email1" /></li>

        <li><label for="age1">Are you above 21 yrs old?</label>
	<input type="radio" name="age1" value="Yes" class="aboveage1" /> Yes
	<input type="radio" name="age1" value="No" class="aboveage1" /> No</li>
</ol>
<ol id="parent1" class="formset">
<li><strong>Parent/Guardian Information:</strong></li>
        <li><label for="pname1">Parent Name: </label>
	<input type="text" id="pname1" value="" name="pname1"/></li>
        <li><label for="contact1">Contact No.: </label>
	<input type="text" id="contact1" value="" name="contact1"/></li>
</ol>
<input type="submit" name="submit" value="Submit" class="submitbtn" />
</fieldset>

Now, let's add in the jQuery.

$(document).ready(function(){
    $("#parent1").css("display","none");
        $(".aboveage1").click(function(){
    	if ($('input[name=age1]:checked').val() == "No" ) {
        	$("#parent1").slideDown("fast"); //Slide Down Effect
        } else {
            $("#parent1").slideUp("fast");	//Slide Up Effect
        }
     });
});

From the jQuery code, we can see that when DOM is ready, it will hide all the elements contain inside the #parent1 selector. When the .aboveage1 is clicked and the value is equal to "No", the hidden #parent1 selector containing all other fields will slide down showing all the extra fields. If the value from the radio button is NOT equal to "No", then the #parent1 selector will slide up hiding away those extra fields.

Now, the form is working! As you admire the effect and simplicity of the new form you'll realized that more options could be achieved using this technique.

Next, you proceed on with writing server side validation for your web form, when a user is below 21 years old and he or she does not enter all the required information for the Parent/Guardian Information section, a validation error message will be prompt.

To your surprise, you notice that the Parent/Guardian Information section is hidden, and when you select "No", it slide open again. Isn't it supposed to remain open even there is an error message? How will the user know that there is problem with the input over at the Parent/Guardian Information section if it is hidden? This make the form more complicated and harder to fill in, instead of making the form simple and easy to use.

Now you are puzzled why does the section close back again? The reason is because once the page refresh, the jQuery reloads thus .css("display","none"); executed again and Parent/Guardian Information section is hidden.

How To Make That Section Stay Open?

As we know that the browser cookie is a small piece of text stored on a user's computer by a web browser. Therefore, one of the way is to use a cookie to store the last state of the form, and based on the cookie value, it can retrieve the last state of the form before the page is refreshed.

Different Between Normal HTTP Cookie And JavaScript Cookie

The HTTP Cookie or JavaScript Cookie are the same type as both of them will be store on an user's browser. The only difference between them is where the cookie is being created.

Server Side Created Cookie - HTTP Cookie

Server side created cookie is generated from server side and sent along with the rest of the HTTP headers when the user request the web page.

Client Side Created Cookie - JavaScript Cookie

Client side cookie are created by the client's browser without returning any request to the server. When a JavaScript event is triggered, the cookie is being created by the client's browser and being store as the normal cookie.

A jQuery Form with jQuery Cookie

From the above example, since we have already loaded in jQuery for our form. We will be using a jQuery Cookie plugin from Stillbuero. It is a simple, lightweight utility plugin that can help us for reading, writing and deleting cookies.

What you need to do is to download the jQuery Cookie plugin, and include it in your HTML head tag. Next, we will take a look at the normal HTML markup.

//Example 2: Display Fields Based On Selected Radio Button With jQuery Cookie
<fieldset></p>
<ol class="formset">
        <li><label for="fname2">First Name: </label>
	<input type="text" id="fname2" value="" name="fname2"/></li>
        <li><label for="lname2">Last Name: </label><br />
	<input type="text" id="lname2" value="" name="lname2"/></li>
        <li><label for="email2">Email Address: </label><br />
	<input type="text" id="email2" value="" name="email2" /></li>
        <li><label for="age2">Are you above 21 yrs old?</label><br />
	<input type="radio" name="age2" value="Yes" class="aboveage2" /> Yes
	<input type="radio" name="age2" value="No" class="aboveage2" /> No</li>
</ol>
<ol id="parent2" class="formset">
        <li><strong>Parent/Guardian Information:</strong></li>
        <li><label for="pname2">Parent Name: </label>
	<input type="text" id="pname2" value="" name="pname2"/></li>
        <li><label for="contact2">Contact No.: </label><br />
	<input type="text" id="contact2" value="" name="contact2"/></li>
</ol>
<input type="submit" name="submit" value="Submit" class="submitbtn" />
</fieldset>

Now, let's create the jQuery code that will help you create the cookie.

$(document).ready(function(){
    $("#parent2").css("display","none");
        $(".aboveage2").click(function(){
    	if ($('input[name=age2]:checked').val() == "No" ) {
            $("#parent2").slideDown("fast"); //Slide Down Effect
            $.cookie('showTop', 'expanded'); //Add cookie 'ShowTop'
        } else {
            $("#parent2").slideUp("fast");	//Slide Up Effect
            $.cookie('showTop', 'collapsed'); //Add cookie 'ShowTop' 
        }
     });  
        var showTop = $.cookie('showTop'); 
        if (showTop == 'expanded') {
      	$("#parent2").show("fast");
        $('input[name=age2]:checked');
      } else {
      	$("#parent2").hide("fast");
        $('input[name=age2]:checked');
      }  
});

From this example, when .aboveage2 is being clicked, you can see that we are assigning a value to a cookie name and store it in the browser. If the web page refresh, the jQuery Cookie plugin will check for the cookie stored in the browser, and it will show or hide the Parent/Guardian Information section accordingly.

With just some additional lines of code, it makes the whole online form user experience much more complete.

What Can jQuery Cookie Be Of Other Use?

Aftermath

I think it's always the little things that make a huge different in the things we do. With jQuery Cookie Plugin, it will make the whole online form experience more inclusive.

If you know of any sites or any other interesting use of using jQuery Cookie, we'll like to know, share it with us in the comment!

Opinions expressed in this article are those of the author and not necessarily those of Onextrapixel.