Display a form field conditionally

Boris Hocdé Updated by Boris Hocdé

You can make a form field appear only if another field matches a condition. For example, you can your visitors how they heard about you. In a dropdown, the visitor can choose the 5 most frequent channels. And a 6th option "Other" makes a free text field appears.

First, create 2 form fields

The first one should be a dropdown to select the default choices:

And the second one is for the free text in case "Other" is selected.

The IDs of the two fields and the value of the "Other" option are used to connect things together.

In our example, we use the field IDs hear_about_us and hear_about_us_other, and the special value other.

In CSS, hide the free text field unless it has a class to make to visible

In our custom CSS tool, add the following snippet to make the free text field appear only if it has a class visible:

[name=hear_about_us_other]:not(.visible) {
display: none;
}

Pay attention to replace hear_about_us_other by the field ID you chose in your form.

In JavaScript, add the visible class when relevant

Now, let's add and remove the class visible to the free text field when it should appear or disappear.

Create a JS callback listening for the event Before popup display, with the following snippet:

var customIfValue = 'other';
var choiceField = event.target.querySelector('select[name=hear_about_us]');
var customField = event.target.querySelector('input[name=hear_about_us_other]');

if (choiceField && customField) {
choiceField.addEventListener('change', function() {
if (this.value === customIfValue) {
customField.classList.add('visible');
} else {
customField.classList.remove('visible');
}
});
}

Ensure to replace other, hear_about_us, and hear_about_us_other by the values you're using in your form.

And voilà! Your free text field will appear if "Other" is chosen. And disappear if another option is selected.

Note that the free text field mustn't be set as required.

How did we do?

Flag a Popup as Clicked With JS Code

Close a Popup With JS Code

Contact