HTML5 required attribute one of two fields

前端 未结 4 1700
刺人心
刺人心 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);
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form method="post">
      Telephone:
      <input type="tel" name="telephone" value="" required>
      <br>Mobile:
      <input type="tel" name="mobile" value="" required>
      <br>
      <input type="submit" value="Submit">
    </form>

    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.

    0 讨论(0)
  • 2021-02-05 03:48

    Based on Andy's answer, but I needed a checkbox implementation & came up with this.

    what role(s) do you want?
    <input type="checkbox" data-manyselect="roler" name="author" required>
    <input type="checkbox" data-manyselect="roler" name="coder" required>
    <input type="checkbox" data-manyselect="roler" name="teacher" required>
    
    where will you work?
    <input type="checkbox" data-manyselect="placement" name="library" required>
    <input type="checkbox" data-manyselect="placement" name="home" required>
    <input type="checkbox" data-manyselect="placement" name="office" required>
    
    jQuery(function ($) {
        // get anything with the data-manyselect
        // you don't even have to name your group if only one group
        var $group = $("[data-manyselect]");
    
        $group.on('input', function () {
            var group = $(this).data('manyselect');
            // set required property of other inputs in group to false
            var allInGroup = $('*[data-manyselect="'+group+'"]');
            // Set the required property of the other input to false if this input is not empty.
            var oneSet = true;
            $(allInGroup).each(function(){
                if ($(this).prop('checked'))
                    oneSet = false;
            });
            $(allInGroup).prop('required', oneSet)
        });
    });
    

    Here for anyone else getting here by googling and wanting a quick solution for one of many checkboxes.

    0 讨论(0)
  • 2021-02-05 03:52

    You would better do form data validation with Javascript anyway, because the HTML5 validation doesn't work in older browsers. Here is how:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Form Validation Phone Number</title>
    </head>
    <body>
        <form name="myForm" action="data_handler.php">
            <input type="tel" name="telephone">
            <input type="tel" name="mobile">
            <input type="button" value="Submit" onclick="validateAndSend()">
        </form>
        <script>
            function validateAndSend() {
                if (myForm.telephone.value == '' && myForm.mobile.value == '') {
                    alert('You have to enter at least one phone number.');
                    return false;
                }
                else {
                    myForm.submit();
                }
            }
        </script>
    </body>
    </html>
    

    .
    Live demo here: http://codepen.io/anon/pen/LCpue?editors=100. Let me know if this works for you, if you will.

    0 讨论(0)
  • 2021-02-05 04:10

    For two text fields @Andy's answer is working awesome, but in case of more than two fields we can use something like this.

    jQuery(function ($) {
        var $inputs = $('input[name=phone],input[name=mobile],input[name=email]');
        $inputs.on('input', function () {
            var total = $('input[name=phone]').val().length + $('input[name=mobile]').val().length + $('input[name=email]').val().length;
            $inputs.not(this).prop('required', !total);
    
        });
    });
    
    0 讨论(0)
提交回复
热议问题