In this post I’ll show you how to set up conditional form fields with Javascript. The very first time I set this up was around 6 years ago when building my contact form. 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. We can use this to target 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. 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(‘change’).

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 our conditions then show the element we hid 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 remove it when something different 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';
  }
}