Using the HTML5 required Attribute for Multiple Elements

Updated

While developing an eCommerce site I was asked by the client if it was possible to add the HTML5 required attribute to the telephone number and mobile number fields. Only one field would actually be required so if a customer entered a telephone number the browser wouldn’t throw an error about the mobile number field being empty and vice versa.

I had a look around online in the usual places; Google, Stack Overflow, MDN et al. to no avail – this isn’t functionality that’s built into HTML5’s form validation so I had to go down the jQuery/JavaScript route instead:

jQuery(function ($) {
    var $inputs = $('input[name=telephone],input[name=mobile]');
    $inputs.on('input', function () {
        // Sets the required property of the other input to false if this input is not empty.
        $inputs.not(this).prop('required', !$(this).val().length);
    });
});

The above code translated into pseudo-English is: WHEN either input fields named ‘telephone’ or ‘mobile’ have their text content edited, IF that field is not empty, make the other field NOT required.

jQuery Plugin

The snippet worked perfectly for my use case but if it’s going to be used more than once it’d make sense to be DRY and make this into a jQuery plugin:

(function ($) {
    $.fn.groupRequired = function () {
        var $inputs = this;

        $inputs.on('input', function () {
            $inputs.not(this).prop('required', !$(this).val().length);
        });
    }
})(jQuery);

Now we can call the jQuery plugin on as many groups of elements as we want:

jQuery(function ($) {
    $('.my-required-group').groupRequired();
    $('input[name=telephone],input[name=mobile]').groupRequired();
    $('form input[type=tel]').groupRequired();
});

I have released a plugin encapsulating the above functionality and included a few more features, you can get it from the project’s Github page or install it with yarn:

yarn add jquery-grouprequired

Post Meta

Filed under: Code
Tags: , ,

About the author


Comments