Conditionalized Structure Fields

Description

This javascript code can be used in a custom field as an example of making fields (in this case "Featured Start" and "Featured End") visible conditionally based on the value of another field.

Read the full explanation at LearndotCMS.com.

Link: http://learndotcms.com/2012/10/conditionalizing-structure-fields/

Image

Conditionalized Structure Fields

Code

// Prevent namespace collisions with Dojo, etc
var j = jQuery.noConflict();
// Function to show/hide fields
function toggleFields(val) {
  if(val == '0') {
    j("${esc.h}featuredStart_tag,${esc.h}featuredEnd_tag").parent().hide();
  } else {
    j("${esc.h}featuredStart_tag,${esc.h}featuredEnd_tag").parent().show();
  }
}

j(document).ready(function() {
  // Hide our custom field's label
  j('${esc.h}conditionalFields_tag').parent().hide();
  // Check the field state on load and show/hide our conditional fields as appropriate
  var startingVal = j("input:radio[name=bool1]").val();
  toggleFields(startingVal);

  // Add click handler to show/hide fields on controlling radio button
  j("input:radio[name=bool1]").click(function() {
    toggleFields(j(this).val());
  });
});