HTML5 required attribute one of two fields

前端 未结 4 1787
刺人心
刺人心 2021-02-05 03:26

I have a form with two required input fields:

4条回答
  •  感动是毒
    2021-02-05 03:48

    Update 2020-06-21 (ES6):

    Given that jQuery has become somewhat unfashionable in the JavaScript world and that ES6 provides some nice syntactic sugar, I have written a pure JS equivalent to the original answer:

    document.addEventListener('DOMContentLoaded', function () {
        const inputs = Array.from(document.querySelectorAll('input[name=telephone], input[name=mobile]'));
        const inputListener = e => inputs.filter(i => i !== e.target).forEach(i => i.required = !e.target.value.length);
    
        inputs.forEach(i => i.addEventListener('input', inputListener));
    });
    

    Note that the above uses arrow functions and Array.from so does not work in IE11 without the use of a transpiler such as Babel.

    Original Answer (jQuery):

    I played around with some ideas and now have a working solution for this problem using jQuery:

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

    This uses the input event on both inputs, and when one is not empty it sets the required property of the other input to false.

    I've written a jQuery plugin wrapping the above JavaScript code so that it can be used on multiple groups of elements.

提交回复
热议问题