Conditional elements

By Ken Hawkins

interactive conditional forms Requires EBI Visual Framework 1.2.0

If you want to show form elements depending on user responses, or any thing else.

Contribute a pattern

Have a great way of doing something, add it to the Style Lab. Here's how


Implementation code

Get a zip with all the sample HTML and any spaecial CSS or JS needed: Download a ZIP file More on how to use this

HTML
<form id="yourID" class="conditional-form">
  <fieldset class="">
    <legend>Choose your favourite</legend>
    <input type="radio" name="pokemon" value="Red" id="pokemonRed" required><label for="pokemonRed">Red</label>
    <input type="radio" name="pokemon" value="Blue" id="pokemonBlue"><label for="pokemonBlue">Blue</label>
    <input type="radio" name="pokemon" value="Yellow" id="pokemonYellow"><label for="pokemonYellow">Yellow</label>
  </fieldset>
  <div class="conditional-div hidden" data-condition="pokemonRed:checked" data-condition-val="Red">
    <label>Why
      <input type="text" placeholder="Why do you like red?">
    </label>
  </div>
  <div class="conditional-div hidden" data-condition="pokemonBlue:checked" data-condition-val="Blue">
    Good choice!
  </div>
  <div class="conditional-div hidden" data-condition="pokemonYellow:checked" data-condition-val="Yellow">
    Terrible choice, try again.
  </div>
</form>



JS
$( document ).ready(function() {
  function conditionalElementsEBI(watchedParentClass) {
    var watchedParentClass = watchedParentClass || '.conditional-form';

    $(watchedParentClass).on('change', function(){
      var activeSet = this;
      $(activeSet).children().each(function(){
        if ($(this).data('condition')) {
          var conditionTarget = '#' + $(this).data('condition'),
              conditionRequirement = $(this).data('condition-val') || 1;

          if ($(conditionTarget).val() == conditionRequirement) {
            $(this).removeClass('hidden');
          } else {
            $(this).addClass('hidden');
          }
        }
      });
    });
  }

  // bootstrap it
  conditionalElementsEBI();
});