Simplifying show/hide logic in your webforms

When working on web forms, the need to show or hide certain elements based on user input is a common requirement. Traditionally, achieving this functionality might involve writing custom JavaScript for each scenario, which can become cumbersome and repetitive.

The Common Challenge

Consider a scenario where you have a form with a <select> element, and you want to show or hide specific sections of the form based on the selected option. Additionally, you might have checkboxes or radio buttons that trigger different visibility scenarios. Handling these situations often requires custom JavaScript code to manage the visibility of elements.

A Simplified Approach with jQuery

To streamline this process, we can leverage jQuery and markup attributes to define show/hide behavior directly in our HTML. This approach makes our code more readable and less prone to errors.

Let’s examine a jQuery snippet that achieves this:

javascriptCopy code

// HTML Example
/*
<select class="uni-toggle" data-triggers-on="#trigger-has-effect-here,.other-effect-area">
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

<div id="trigger-has-effect-here" class="hidden" data-trigger-value="1">Hidden stuff</div>
<div class="other-effect-area hidden" data-trigger-value="2">Hidden stuff</div>
*/

// jQuery Code
(function ($) {
    "use strict";

    $(document).ready(function () {
        $(".uni-toggle").each(function () {
            universal_toggle($(this));
            $(this).change(function () {
                universal_toggle($(this));
            });
        });
    });

    function universal_toggle(trigger) {
        var selectedValue = getSelectedValue(trigger);
        var areasToShowHide = trigger.data('triggers-on').split(',');

        $(areasToShowHide.join(', ')).each(function () {
            $(this).addClass('hidden');
            if ($(this).data('trigger-value') == selectedValue) {
                $(this).removeClass('hidden');
            }
        });
    }

    function getSelectedValue(trigger) {
        var fieldType = trigger.prop('type');
        if (fieldType === 'select-one') {
            return trigger.val();
        } else if (fieldType === 'checkbox' || fieldType === 'radio') {
            return trigger.filter(':checked').val();
        } else {
            return trigger.val();
        }
    }

})(window.jQuery);

The Benefits

  1. Simplicity Through Markup: By using data attributes in the HTML, we define the logic for showing/hiding elements directly in the markup. This makes the code more transparent and easier to maintain.
  2. jQuery Magic: The jQuery script automatically handles the visibility based on the selected option or input value. It reduces the need for custom JavaScript for every scenario.

Resources for Further Learning

  • Book Reference: For a comprehensive guide on JavaScript, consider checking out “Eloquent JavaScript” by Marijn Haverbeke.
  • Video Tutorial: Watch “JavaScript Fundamentals” by The Net Ninja on YouTube for a beginner-friendly introduction to JavaScript concepts.

Framework Agnostic

While this example uses jQuery, the concept is framework-agnostic. If you prefer pure JavaScript, the same logic can be implemented without jQuery, providing flexibility based on your project requirements.

By adopting this approach, you enhance both the maintainability of your code and the overall user experience on your web forms.

Note: This solution was implemented in a Laravel environment, but the principles can be applied universally.