Create Conditional Form Fields With jQuery - formalist

Create Conditional Form Fields With jQuery - formalist

Just another jQuery plugin that adds conditional logic to your HTML form that dynamically and conditionally toggling visibility of form fields using HTML data attributes. Supports cascading form fields.

1. Download and insert the jquery.formalist.js script after jQuery library and we're ready to go.

<script src="https://code.jquery.com/jquery-1.12.4.min.js" 
        integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" 
        crossorigin="anonymous">
</script>
<script src="jquery.formalist.js"></script>

2. Add the data-show and data-hide attributes to elements that should be affected by the values selected from form fields.

<form id="form-demo">
  <div class="box">
    <label><input type="checkbox" id="jquery" />jQuery</label>
    <label><input type="checkbox" id="script" />Script</label>
  </div>
  <div class="box" data-show="jquery">
    You choose the "jQuery"
  </div>
  <div class="box" data-show="script">
    You choose the "Script"
  </div>
</form>

3. Call the function on the html form and done.

$(function(){
  $('#form-demo').formalist();
});

4. Show/hide the elements.

form .hidden { display: none; }
form .visible { display: block; }

5. Default plugin options and callback functions.

$('#form-demo').formalist({
  // default selector
  selector: ':radio,:checkbox,select',
  // trigger event
  event: 'change',
  // default box
  box: 'div.box',
  // cascading elements
  cascade: ':radio:checked:visible,:checkbox:checked:visible,select:visible option:selected',
  // default CSS classes
  classwhenhidden: 'hidden',
  classwhenvisible: 'visible',
  // callback functions
  hide: function(box) {hide(box);},
  show: function(box) {show(box);},
  correlate: function(box, field, type, value, name, id) {return correlate(box, field, type, value, name, id);}
  
});

This awesome jQuery plugin is developed by xavierfoucrier. For more Advanced Usages, please check the demo page or visit the official website.

  • Publication date: 04.01.2018
  • Source