简体   繁体   中英

check if all input field has value jQuery condition

i have several input fields with a class name of required .

i have a code below to check if all my <input> fields have a value, if not empty or null, it will show/unhide a specific div .

but it doest seem to work on me.

also, by default, #print is displayed as none via CSS.

<!-- index.php -->

<input type="text" id="getID" class="required form-control" placeholder="id">
<input type="text" id="getName" class="required form-control" placeholder="name">

<!-- script.js -->

$(document).ready(function() { 
  $('input.required').each(function() { 
    if($(this).val() != "") {
        $("#print").show();
    }
    else {
        $("#print").hide();
    }
  });
});

I'd suggest:

$('#print').toggle(!($('input.required').length == $('input.required').filter(function () {
        return this.value;
    }).length));

Simplified JS Fiddle demo .

Obviously this should be run on submit , assuming you want to only show the #print element as a validation prior to submission.

References:

As I stated in my comment above, you're checking the values when the page loads, before the user has any chance to enter anything. If you have a button on your page, bind the event to that which will fire the function at the right time.

Something a little like this jFiddle

index.php

<input type="text" id="getID" class="required form-control" placeholder="id">
<input type="text" id="getName" class="required form-control" placeholder="name">
<div id="button">Submit</div>
<div id="print">You're missing something D:!</div>

script.js

$('#button').on('click', function() { 
    $('#print').hide();
    var error=false;
    $('input.required').each(function() { 
        if($(this).val() == "") {
            error=true;
        }
    });
    if(error) {
        $('#print').show();   
    }
});

Try

$(document).ready(function () {
    //the default state
    var valid = true;
    $('input.required').each(function () {
        //if the value of the current input is blank then the set is invalid and we can stop the iteration now
        if ($.trim(this.value) == '') {
            valid = false;
            return false;
        }
    });
    //set the visibility of the element based on the value of valid state
    $("#print").toggle(!valid);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM