Skip to content

Instantly share code, notes, and snippets.

@prashantdsala
Created September 13, 2024 08:26
Show Gist options
  • Save prashantdsala/edaae21f2b6fa78af6a6e5910c451e08 to your computer and use it in GitHub Desktop.
Save prashantdsala/edaae21f2b6fa78af6a6e5910c451e08 to your computer and use it in GitHub Desktop.
Drupal show hide field based on the selected value
/**
* @file
* Preview behaviors.
*/
(function ($, Drupal) {
Drupal.behaviors.conditional_fields = {
attach(context) {
// Hide the help text initially.
$(once('field_organization_details', '[name="field_organization_details[0][subform][field_leagally_incorporated]"]', context)).each(function () {
var description = $(this).siblings('.form-item__description');
showHide($(this).val(), 'no', description);
$('[name="field_organization_details[0][subform][field_leagally_incorporated]', context).on('change', function() {
showHide($(this).val(), 'no', description);
});
});
// // Show or hide the field description based on the value.
function showHide(currentValue, valueToMatch, field) {
currentValue === valueToMatch ? field.show() : field.hide();
}
// Helper function to set up the change event and handle show/hide logic.
function setupConditionalField(fieldName, matchValue) {
// Build the field selector dynamically.
var fieldSelector = `[name="${fieldName}"]`;
// Attach behavior to the field using once to avoid multiple bindings.
$(once(fieldName, fieldSelector, context)).each(function () {
var description = $(this).siblings('.form-item__description');
// Initial check to show or hide the description.
showHide($(this).val(), matchValue, description);
// Handle the change event to toggle description based on the value.
$(this).on('change', function () {
showHide($(this).val(), matchValue, description);
});
});
}
// Helper function to show or hide the field description based on the value.
function showHide(currentValue, valueToMatch, field) {
currentValue === valueToMatch ? field.show() : field.hide();
}
// List of fields and match values.
var fieldsToMonitor = [
{
fieldName: 'field_organization_details[0][subform][field_leagally_incorporated]',
matchValue: 'no'
},
{
fieldName: 'field_data_and_privacy_essential[0][subform][field_explicit_user_consent]',
matchValue: 'no'
}
// Add more fields if needed
];
// Loop through each field and set up the show/hide logic.
fieldsToMonitor.forEach(function (fieldConfig) {
setupConditionalField(fieldConfig.fieldName, fieldConfig.matchValue);
});
}
};
})(jQuery, Drupal);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment