HTML5 Articles - Blog - Andy Palmer Personal website of Andy Palmer - A Web Developer based in Exeter, Devon Fri, 03 Nov 2017 12:32:50 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.2 Using the HTML5 required Attribute for Multiple Elements /blog/code/using-html5-required-attribute-for-multiple-elements/ /blog/code/using-html5-required-attribute-for-multiple-elements/#respond Tue, 04 Oct 2016 17:32:39 +0000 https://andypalmer.me/?p=55 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 […]

The post Using the HTML5 required Attribute for Multiple Elements appeared first on Andy Palmer.

]]>
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

The post Using the HTML5 required Attribute for Multiple Elements appeared first on Andy Palmer.

]]>
/blog/code/using-html5-required-attribute-for-multiple-elements/feed/ 0