jQuery Tutorial: Hide or Display a Field Based on the Value of Another Field

Comments 10 Standard

Gah I know it’s been a while since I’ve posted something and I try to post every month but I’ve been busy programming games for myself and my clients (which is a good thing!). But here’s some yummy coding snippets to make your life easier.

Creating the Form

For this example let’s assume that we have a game which requires parental emails or parental permission to play if the member who is signing up is under 13 years of age* (good ole COPPA). Create an php file with the following contents:

<html>
<head>
    <title>Test Hide/Show Fields</title>
    <script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script language="javascript" type="text/javascript" src="showhide.js"></script>
</head>
<body>
    <?php
        //this will show you the values in the form the data when you hit the submit button
        if ($_POST) {
            echo "Form was submitted, here are the form values: <pre>";
            print_r($_POST);
            echo "</pre>";
        }
    ?>
    <form method="POST">
        <p>Name: <input type="text" name="player_name" /></p>
        <p>Email: <input type="text" name="player_email" /></p>
        <p>Age: 
             <select id="age" name="age">
             <?php
                  //sorry but if you're over 30 you're too old to join, lol
                  for ($age = 6; $age <= 30; $age++)
                       echo "<option value=\"$age\">$age</option>
             ?>
             </select>
        </p>
        <div id="parentPermission">
                <p>Parent's Name: <input type="text" name="parent_name" /></p>
                <p>Parent's Email: <input type="text" name="parent_email" /></p>
                <p>You must have parental permission before you can play.</p>
        </div>
        <p align="center"><input type="submit" value="Join Game!" /></p> 
 </form>
</body>
</html>

Writing the jQuery Code

Now all that’s left is to write the code that will show (or hide) the fields we want to display when the user has selected a specific value in our selection drop down list. Create a file called showhide.js and save it to the same location as the form you created in the previous step.

/**
* File: js/showhide.js
* Author: design1online.com, LLC
* Purpose: toggle the visibility of fields depending on the value of another field
**/
$(document).ready(function() {
    toggleFields(); //call this first so we start out with the correct visibility depending on the selected form values
   //this will call our toggleFields function every time the selection value of our underAge field changes
    $("#age").change(function() { toggleFields(); });

});
//this toggles the visibility of our parent permission fields depending on the current selected value of the underAge field
function toggleFields()
{
    if ($("#age").val() < 13)
        $("#parentPermission").show();
    else
        $("#parentPermission").hide();
}

Summary

Now every time you select an age below 13 you will see the parent permission form fields displayed. If you select an age 13 or older the parent permission fields will disappear. This is useful if you have conditional data you want to collect based on a specific value or selection response. Hope it helps!

*Note

The age field in this example is just to show you how you can show/hide fields depending on the value selected. If you intend to store the age of a person in your database you need to store their date of birth since age changes every year.

Demo and working code

Try our JSFiddle demo to see this code in action!

Advertisements

10 thoughts on “jQuery Tutorial: Hide or Display a Field Based on the Value of Another Field

  1. Thanks so much for posting. If you were to use a data attribute instead of a value such as , how would you go about doing that in the jQuery? if ($(“#age”).data(‘id’) < 13) or if ($("#age").attr('data-id') < 13) doesn't seem to work. Thanks for your help.

  2. Sorry about that, part of my message was removed … such as, value=”somevalue” data-id=”6″ …

  3. First of all you should make sure that it’s interpreting it as an integer value. Also I would recommend a better description for your data value. Data-id doesn’t really tell you what the data is for but data-age does:

    if (parseInt($("#age").data("age")) < 13)

    Then your select should look like this, the data needs to go on the options and not on the select tag:

     
      <?php
                      //sorry but if you're over 30 you're too old to join, lol
                      for ($age = 6; $age <= 30; $age++)
                          echo "<option value=\"$age\" data-age=\"$age\">$age </option>
      ?>
    
  4. The fiddle code look great but when I tried to replace it with my code it won’t toggle. Here is my code:

    Toggle fields based on form values

    Business:

    Sell
    Buy
    Both
    Trade
    Freight
    Customs

    Service Type:

    Air Cargo
    Couriers
    Freight Forwarder

    Tollfree Number:

    Your Email Address:

    Services:

    ACA
    AFF

    Products/Services:

    Brand Names:

    The Javascript code is:

    $(‘:checkbox’).click(function() {
    $(‘input[name=products]’).val(
    $(‘:checkbox:checked’).map(function() {
    return $(this).val();
    }).get().join(‘,’)
    );
    });

    $(document).ready(function () {
    toggleFields();
    $(“#business”).change(function () {
    toggleFields();
    });

    });
    function toggleFields() {
    if ($(“#business”).val() == 1 || ($(“#business”).val() == 2 || ($(“#business”).val() == 3)
    $(“#brand”).show();
    $(“#freight”).hide();
    $(“#customs”).hide();
    else
    if ($(“#business”).val() == 5)
    $(“#brand”).hide();
    $(“#freight”).show();
    $(“#customs”).show();
    else
    $(“#brand”).hide();
    $(“#freight”).hide();
    $(“#customs”).hide();
    }

    I am trying to achieve two things in the above jQuery: One is to toggle 3 sections (id = brand, freight, customs) base on the “business” field. But it’s not doing it. It’s probably something simple but I am scratching my head for a long time.

    Secondly I want to check the “services” field checkbox so that when I select the checkbox it is supposed to populate the “products” field but it’s not doing it. This was simply based on http://jsfiddle.net/dTrVt/18/ But it’s not working either.

    I put both in your jsfiddle using 1.8.3 and it’s not working. I try other versions too but same result. Your help is greatly appreciated.

  5. Oops looks like the blog took away the format for the html. This is encoded version:

    <h1>Toggle fields based on form values</h1>
    <form method="POST">
    <table cellspacing="2" cellpadding="2">
    <tr>
    <td valign="top" /><b>Business:</b>
    <td><select id="business" name="business" >
    <option value="1">Sell</option>
    <option value="2">Buy</option>
    <option value="3">Both</option>
    <option value="4">Trade</option>
    <option value="5">Freight</option>
    <option value="6">Customs</option>
    </select>
    </td>
    </tr>

    <div id="freight">
    <tr>
    <td><b>Service Type:</b></td>
    <td><select name="type">
    <option value="1">Air Cargo</option>
    <option value="2">Couriers</option>
    <option value="3">Freight Forwarder</option>
    </select>
    </td>
    </tr>
    <tr>
    <td><b>Tollfree Number:</b></td>
    <td><input type="text" name="tollfree" />
    </td>
    </tr>
    </div>
    <tr>
    <td valign="top"><b>Your Email Address:</b></td>
    <td><input type="text" name="email" /></td>
    </tr>
    <div id="customs">
    <tr>
    <td /><b>Services:</b>
    <td>
    <input type="checkbox" value="ACA – Air Cargo Agent" />ACA – Air Cargo Agent<br />
    <input type="checkbox" value="AFF – Air Freight Forwarder" />AFF – Air Freight Forwarder<br />
    </td>
    </tr>
    </div>
    <tr>
    <td><b>Products/Services:</b></td>
    <td><input type="text" name="products" size="40" /></td>
    </tr>
    <div id="brand">
    <tr>
    <td><b>Brand Names:</b></td>
    <td><input type="text" name="brands" /></td>
    </tr>
    </div>
    </table>
    </form>

  6. How to use string instead of numeric value in the option, when i change to text/string seem it wont trigger
    Here is my source code. Thanks in advance…

    Please Pick One Of :

    AAAA
    BBBB
    CCCC

    Karena Muda Kamu Butuh Ijin Orang Tua Ya Nak :
    Parent’s Name:

    Parent’s Email:

    $(document).ready(function () {
    toggleFields(); //call this first so we start out with the correct visibility depending on the selected form values
    //this will call our toggleFields function every time the selection value of our underAge field changes
    $(“#mycmb”).change(function () {
    toggleFields();
    });

    });
    //this toggles the visibility of our parent permission fields depending on the current selected value of the underAge field
    function toggleFields() {
    if ($(“#mycmb”).val() = “A”)
    $(“#parentPermission”).show();
    else
    $(“#parentPermission”).hide();
    }

  7. aaarrgh the blog took away the code, but i am sure you know what i mean,
    my option is AAAA AAAA, if i change the value into number, it work flawlessly.

  8. You have a syntax error. It should be if ($(“#mycmb”).val() == “A”). Two equal signs is a comparison of two values to see if they are the same, One equal sign means you want to set the value.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s