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

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

[tut demo=”http://www.onextrapixel.com/examples/jquery-cookie/” download=”http://www.onextrapixel.com/examples/jquery-cookie/jquery-cookie.zip”]

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?

[tut demo=”http://www.onextrapixel.com/examples/jquery-cookie/” download=”http://www.onextrapixel.com/examples/jquery-cookie/jquery-cookie.zip”]

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!

Comments

    • Jason,
    • January 23, 2010
    / Reply

    Thanks for the tutorial!

    I’m wondering… how would you go about displaying the form field based on a selection from a drop down menu (opposed to a radio button)?

    I assume you would re-write this part somehow:

    $(‘input[name=age1]:checked’).val()

    I tried:

    $(‘select[name=age1]:checked’).val()

    but I had no luck. Any suggestions?

    1. / Reply

      You will need to use .change()

      This can be something you looking for jQuery Change.

      ;)

  1. / Reply

    I must be using something similar to

    “A pop up lightbox appears when you visit the site for the first time. Once you close it, it will create a cookie and save in your browser. The next time you visit the pop up lightbox will not appear.

    Real Example: Wefollow”

    but mine should expire in 2 days… just having some problems modifying it to wait to load… as well as incrementing the cookie so if they have only seen it once it will show 2 full times during their visit.

    Also looking for code to show on close. oh btw using thickbox not lightbox and using jquery.cookie.js

    • Baiju Thomas,
    • June 23, 2010
    / Reply

    For drop down change use this

    $(document).ready(function(){
    $(“#parent2”).css(“display”,”none”);

    $(“select”).change(function () {
    if ($(‘select option:selected’).val() == “No” ) {
    $(“#parent2”).slideDown(“fast”); //Slide Down Effect
    $.cookie(‘showTop’, ‘expanded’);
    }
    }

    • John,
    • November 5, 2010
    / Reply

    I am having trouble getting this to work with more than one option in a select box. For some reason, I can only get one option to work. Here’s what I have:

    $(document).ready(function(){

    $(“#thestore”).css(“display”,”none”);
    $(“#thegroup”).css(“display”,”none”);
    $(“#theuser”).css(“display”,”none”);

    $(“#recip”).change(function () {
    if ($(‘#recip option:selected’).val() == “1” ) {

    $(“#thestore”).slideDown(“fast”); //Slide Down Effect

    } else if ($(‘#recip option:selected’).val() == “2” ) {

    $(“#thegroup”).slideDown(“fast”); //Slide Down Effect

    } else if ($(‘#recip option:selected’).val() == “3” ) {

    $(“#theuser”).slideDown(“fast”); //Slide Down Effect

    } else {

    $(“#thestore”).slideUp(“fast”); //Slide Up Effect
    $(“#thegroup”).slideUp(“fast”); //Slide Up Effect
    $(“#theuser”).slideUp(“fast”); //Slide Up Effect
    }

    }); // End recip change function
    }); // End document ready function

    Then on the form:

    Select One
    Entire Store
    Entire Group
    Individual

    To store:

    To group:

    To employee:

    Could you tell me what I’m doing wrong?

    • John,
    • November 5, 2010
    / Reply

    P.S.- My above comment did not display the HTML for the select box and hidden div’s correctly, but I think you can figure out what’s going on.

    • erty,
    • January 12, 2011
    / Reply

    frt

    • Rachel,
    • February 3, 2011
    / Reply

    Great – thanks for sharing, exactly what I needed :)

    • Jon,
    • February 17, 2011
    / Reply

    thanks! this great! I’m only noticing that on refresh it doesn’t retain the radio button in the option you selected. It instead returns to show nothing chosen. Do you know what the issue is for that and how to resolve it?

  2. / Reply

    Excellent code ! I managed to get a Drop Down Selection method work instead of radio buttons. A previous poster gave an incomplete solution.

    If some of you encounter problems with the code ( selection not saved / shown etc ), it’s because of your browsers security settings, either Javascript is not (fully) supported or Cookies are restricted, etc.

    Here is the code for both control.js and a sample HTML form based on the original one: http://pastebin.com/a0kbTvd8
    Pastebin is a place where you paste your stuff, so it’s not spam or anything. Note that I only used the Cookie option since it’s 99.9% always needed.

    Thanks to original creator for a great script !

    • Yuanzhong Deng,
    • June 3, 2011
    / Reply

    How about more than 2 options?

    Not ‘Yes’ or ‘No’, But ‘A’, ‘B’, ‘C’, ‘D’…

    Especially how to use cookie when there are more than 2 options?

    Thank you.

      • helpful,
      • June 14, 2011
      / Reply

      Yuanzhong Deng,

      You will find the code for using 3 radio buttons here:

      http://jsfiddle.net/8p7J2/2/

    • Marisa,
    • June 10, 2011
    / Reply

    First – thanks for the code – it works great!

    But I can only use it for 1 set of radio buttons with a hidden element.

    How would you code to allow more than one set of radio buttons and hidden fields in the same form?
    I’ve described a ‘normal’ form where there is more than one independent set of radio buttons each with a hidden field revealed by the selection of the right radio button.

    Here is what I mean:

    Form:

    Radio button set 1 (Yes/Maybe/No)
    Hidden field 1 (revealed base on ‘Yes’ radio button selected)

    Radio button set 2 (Hot/Warm/Cold)
    Hidden field 2 (revealed base on ‘Cold’ radio button selected)

    Radio button set 3 (Beer/Wine/Spirits)
    Hidden field 3 (revealed base on ‘Wine’ radio button selected)

    How is this represented in the same $(document).ready(function(){ ?

    Thank you

    • helpful,
    • June 14, 2011
    / Reply

    Marisa,

    You will find the code for using 3 radio buttons here:

    http://jsfiddle.net/8p7J2/2/

      • MikeGTS,
      • July 10, 2011
      / Reply

      Real good help! I’m finding it hard to make it remember the 3rd Radio Button with cookie upon refresh. It gets back to the second one. Can any one help ? It is based on this code:

      http://jsfiddle.net/8p7J2/2/

      Thanks a lot !

        • MikeGTS,
        • July 10, 2011
        / Reply

        I think i found out myself, the following code remembers the state of the 3rd radio button. if anyone can find a better solution pls post.

        THANKS!

    • MikeGTS,
    • July 10, 2011
    / Reply

    the site did not allow me to paste javascript, here’s the js code related to my above post:

    http://pastebin.com/jcEJEHMm

    • MikeGTS,
    • July 10, 2011
    / Reply

    this code introduces the first radio button as a usable ID element, instead of it being empty.

    http://pastebin.com/ARaC0KH8

    • Aneesh Kumar,
    • July 24, 2011
    / Reply

    Great post! I have a similar problem: I want to show different form fields based on a drop-down selection. Ex:

    Selection = bank account:
    – Show account number, routing number, checking/saving

    Selection = debit/credit card:
    – Show card number, expiry month, expiry year, CVV

    Any suggestions?

    Thanks in advance.

    • Chris,
    • August 10, 2011
    / Reply

    Nice script!

    I’ve got a question:

    This function only works with items when I try it. Is there a way to make it work with tabel elements? ()

    regards

    • Chris,
    • August 10, 2011
    / Reply

    I cant edit my older comment, but I ment to type < table[close bracket],< tr[close bracket] and< td[close bracket] between those brackets

    • Myra,
    • December 4, 2011
    / Reply

    Thank you very much for the code. It was very useful to me as I needed to create a form with the possibility to show or hide components depending on the user’s choices.

    • josh,
    • December 8, 2011
    / Reply

    this function is not working within a modal window. any ideas?

    • Kevin,
    • January 31, 2012
    / Reply

    Hello Terrance
    I have a query; what if the data fields that are allowed to show are required? I have tried the code above which works. However, when clicking the radio button option that does not require the drop down, after filling in the form, the hidden fields are still ‘required’ and so the sender is being shown an error.
    Do you have a solution to that problem?
    Thank you.

    • Rob,
    • February 17, 2012
    / Reply

    The first line in the CSS sheet removes borders around textarea’s, but if I remove the border:0 line, it puts a border around the entire section, is there a way to keep borders on textarea tags but still remove them from the section?

    This is very simple and works very well besides the border issue.

    Thank you.

      • Rob,
      • February 17, 2012
      / Reply

      Disregard, I am an idiot, just added textarea to the CSS and matched the border and background.

      Thanks again for providing this free.

    • Anthony Elmore,
    • April 22, 2014
    / Reply

    I hope someone’s still using this thread:

    How can I get it to work for more than one selection. It’s not liking the elseIf statement:

    $(document).ready(function(){
    $(“#parent1”).css(“display”,”none”);

    $(“select”).change(function(){
    if ($(‘select option:selected’).val() == “table1” ) {
    $(“#parent1”).slideDown(“fast”); //Slide Down Effect
    } else {
    $(“#parent1”).slideUp(“fast”); //Slide Up Effect
    }
    });

    $(“select”).change(function(){
    if ($(‘select option:selected’).val() == “table3” ) {
    $(“#parent1”).slideDown(“fast”); //Slide Down Effect
    } else {
    $(“#parent1”).slideUp(“fast”); //Slide Up Effect
    }
    });
    });

Leave a Reply

Your email address will not be published. Required fields are marked *

Deals