Show/hide a form question

PRE-REQUISITES
See the following article before reading the below - Form JS APIs | Fliplet Developers Documentation

Show or hide certain questions (fields) in a form (survey)

You may wish to hide certain form fields (aka form questions) from certain users because the question may not be relevant to them. Fliplet’s form builder API lets you ‘toggle’ a field on or off to show or hide it. Setting the toggle to ‘true’ shows the form field, whereas setting the toggle to ‘false’ hides the form field. If ‘true’ or ‘false’ is not specified, the form field will be changed to what it wasn’t before (ie, if it was visible (true) it will become hidden (false) or vice versa).

The example below changes the form field with the field name “question-1” (You can set the field name in the form component settings). It assumes you only have one form on the screen and selects it (if you have multiple forms, you need to specify a form name. See here).

JavaScript

// Hide the field
Fliplet.FormBuilder.get()
  .then(function (form) {
    form.field('question-1').toggle(false);  
  });

// Show the field
Fliplet.FormBuilder.get()
  .then(function (form) {
    form.field('question-1').toggle(true);
  });

// Switch the field's visibility to the opposite of what it was
Fliplet.FormBuilder.get()
  .then(function (form) {
    form.field('question-1').toggle();
  });

Taking the example a step further, you may want to hide a form question based on a user’s response to a previous question. For example, we may have the following questions:

Question-1: What is your favourite color? Which has a multi-choice answer of: Red, Green or Blue

Question-2: What type of Blue? Which has a multi-choice answer of: Aquamarine, Navy or Cerulean

Question-2 is only relevant if a user has answered the previous question with ‘Blue’. Otherwise, it doesn’t make sense and we don’t want to show it.

JavaScript

Fliplet.FormBuilder.get()
  .then(function (form) {
    // Hide the blue type question
    form.field('question-2').toggle(false);
  
    // When user selects a color
    form.field('question-1').change(function (val) {
      if (val === 'Blue') {
        form.field('question-2').toggle(true);
      } else {
        form.field('question-2').toggle(false);
      }
    });
  });

To do this with code, we initially hide Question-2 and set up a trigger to run when Question-1 has been completed.

Once Question-1 has been completed, our code then checks the answer given to Question-1.

If the answer is Red or Green, we keep Question-2 hidden, if it is Blue, we show Question-2 and make it a required question so the user has to answer it (Question-2 can’t be a required question if it’s not shown to a user as it would mean they couldn’t submit a form).