Check all input fields have been filled out with jQuery

前端 未结 4 1041
轻奢々
轻奢々 2020-12-08 14:12

I have 3 divs, each with a dfew input fields and next button on. I want to write a snippet of jQuery that when the next button is clicked it checks to ensure all input fiel

相关标签:
4条回答
  • 2020-12-08 14:34

    Because there is no jQuery selector for this case you can extend jQuery’s selector capabilities.

    Assuming you select all :text elements, the extension is:

    $.extend($.expr[':'],{
         isEmpty: function(e) {
             return e.value === '';
         }
    });
    

    Hence, you can select all empty text fields:

    $(this).closest('div').find(':text:isEmpty');
    

    $.extend($.expr[':'], {
      isEmpty: function (e) {
          return e.value === '';
      }
    });
    $('.next').click(function () {
          var missingRequired = $(this).closest('div').find(':text:isEmpty');
      console.log('Empty text fields: ' + missingRequired.length);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div>
        <input type="text" /><br />
        <input type="text" /><br />
        <input type="text" /><br />
        <input type="submit" value="next" class="next" />
    </div>
    <div>
        <input type="text" /><br />
        <input type="text" /><br />
        <input type="text" /><br />
        <input type="submit" value="next" class="next"  />
    </div>
    <div>
        <input type="text" /><br />
        <input type="text" /><br />
        <input type="submit" value="next" class="next"  />
    </div>

    0 讨论(0)
  • 2020-12-08 14:49
    $('.next').click(function() {
        var inputs = $(this).parent().find('input[value=""]');
        if (!inputs.length) {
            // you have empty fields if this section is reached
        }
    });
    
    0 讨论(0)
  • 2020-12-08 14:50

    You could use filter to reduce the set of all input elements to only those that are empty, and check the length property of what remains:

    $(".next").click(function() {
        var empty = $(this).parent().find("input").filter(function() {
            return this.value === "";
        });
        if(empty.length) {
            //At least one input is empty
        }
    });
    

    Note that the definition of empty in the above code is an empty string. If you want to treat blank spaces as empty too, you may want to trim the value before comparing.

    Also note that there is no need to pass this into jQuery inside the filter function. The DOM element itself will have a value property, and it's much faster to access that instead of using val.

    Here's an updated fiddle.

    0 讨论(0)
  • 2020-12-08 14:59
    $('.next').click(function() {
        var emptyInputs = $(this).parent().find('input[type="text"]').filter(function() { return $(this).val() == ""; });
        if (emptyInputs.length) {
            alert('Fail!');
        }
    });
    
    0 讨论(0)
提交回复
热议问题