Graphics Cove

Conditional Form Fields with Javascript

In this post I'll show you how to set up conditional form fields with Javascript. The very first time I needed this was around 6 years ago when I first built the first version of graphicscove.com. The requirement hasn't come up again since then, until now.

The below snippet uses jQuery. If you're not using jQuery on your site there's a vanilla Javascript alternative at the end of the post.

$(function(){
    $('#hide1').hide();$('#awesome').change(function() {
        if ($('#awesome').val() == 'More Fields') {
            $('#hide1').show();
        }
        else {
            $('#hide1').hide();
        }
    });
});

Code breakdown

The first part of the code hides all the fields we want to show later based on the user selection. This can be used on a wrapper div or on an individual element.

$('#hide1').hide();

Next we set up our listener to detect when an element on the form has changed and if we should show our hidden content. For this we target the element, in this case a select, and listen for a change event when an option is selected.

$('#awesome').change(function() {});

.change() is used as a shorthand for .on('http://api.jquery.com/on/'). A simple if statement within the change listener will check to see if the correct option has been selected. Here we are checking the value of the select to determine true or false. If the value matches the one that needs to show additional content then return true and show the element we hide earlier. If not then hide the element.

if ($('#awesome').val() == 'More Fields') {
    $('#hide1').show();
} else {
    $('#hide1').hide();
}

We don't just want to show the element when a specific value is selected from the dropdown but also to take action when something else has been selected. For example the user could select our target value and show the hidden fields, then change their mind and select something else, leaving the hidden elements visible.

Vanilla Javascript Alternative

If you've chosen to go the vanilla Javascript route and avoid loading another 3rd party dependency, use the below snippet to set up conditional form fields.

document.getElementById('#hide1').style.display = 'none';
var value = e.options[e.selectedIndex].value;
function selectOptionsupdated(select){
    if (value === 'More Fields') {  
        document.getElementById('#hide1').style.display = 'block';
    }
}

© 2010 - 2023 Graphicscove

TwitterFacebookFAQsPrivacy PolicyFree Website Review