简体   繁体   中英

Check if all inputs are empty (have no value)

I am just trying to throw together something quickly that checks to see if any of the inputs in my form are empty.
I am trying this:

var isEmpty = true;
$('input').each(function(){
    if($(this).val() === ""){
        isEmpty = false;
    }
});
alert(isEmpty);

but it keeps alerting true .
If I do this:

$('input').each(function(){
    alert($(this).val();
});

it will alert for every input field I have...
Why is it not returning false if I have an empty input?

Here's a small snippet to check for all your text inputs are empty:

var isEmpty = $("input[type='text']").filter(function () {
    return this.value.trim();
}).length === 0;

console.log( isEmpty );   // boolean true/false

jsBin playground

PS: For checkbox and radio the game is simpler:

var isUnchecked      = $("input[type='checkbox']:checked").length === 0;
var isRadioUnchecked = $("input[type='radio']:checked").length === 0;

BONUS: :blank custom selector (appliable to any element)

 jQuery.extend(jQuery.expr[':'], { blank: function(e,i,m) { if(/input|textarea/i.test(e.tagName)) { if(/checkbox|radio/i.test(e.type)){ return !e.checked; }else{ return !e.value.length; } }else{ return !e.innerHTML.trim(); } } }); $("div:blank").css({outline:"2px solid red"}); $("input:blank").css({outline:"2px solid red"}); $("textarea:blank").css({outline:"2px solid red"}); $("div:not(:blank)").css({outline:"2px solid green"}); // how cool is that? Using :not 
 *{margin:5px;padding:2px;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div></div> <div>Example using :not(:blank) selectors</div> <input type="text" value="abc"> <input type="text" value=""> <input type="checkbox"> <input type="checkbox" checked> <input type="radio" checked> <input type="radio"> <textarea></textarea> <textarea>abc</textarea> 

On standard elements like <div> or <p> etc, :blank acts differently from jQuery's :empty selector cause notice the spaces and newlines:

 <p>

 </p>

and see the results:

$("p:blank").length // 1 (found one blank paragraph)
$("p:empty").length // 0 there's no empty paragraph (since the newlines/spaces)

Back to your question :)

Since you're looping all your elements , currently you're only setting the value of isEmpty to the last element in loop - value.
You could assert your boolean flag into the if like:

var isEmpty = false; // start with a falsy presumption
$('input').each(function(){
    // as long as `isEmpty` is `false`
    if(isEmpty===false && $.trim( this.value ) === "") {
        isEmpty = true;
    }
});

also, checking for emptiness doing === "" makes more sense to return true

otherwise the other way around is inverting your negation

var isEmpty = true; // start with a truthy presumption
$('input').each(function(){
    if(isEmpty && $.trim( this.value )){
        isEmpty = false;
    }
});

Here's a live example:

 var isEmpty = true; // start with a truthy presumption $('input').each(function(){ if(isEmpty && $.trim( this.value )){ isEmpty = false; } }); alert(isEmpty); // false 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" value=""> <input type="text" value="something"> <input type="text" value=""> 

alert is outside the loop , so it will alert only the final value.Hope this below code is useful

HTML

<input type="text" id=" " value="rdrdr"/>
<input type="text" id=" " value=" "/>
<input type="text" id=" " value="xdxd"/>
<input type="text" id=" " value=" "/>

JS

$('input').each(function(){
    var isEmpty = true;
    if($.trim($(this).val()) == ""){
        isEmpty = false;
    }
    console.log(isEmpty)
});

Chexk here for demo

In your code, you're checking:

if($(this) === "")

but $(this) is a jQuery object, which is never identical to the empty string. Perhaps you intended to write this?

if ($(this).val() === "")

您需要检查每个输入的val(),所以请记住获取要比较的值:

if ( $(this).val() === "" )

Try to initialize the variable first, not containing any value. Then place a value when it is a certain scope and call it.

var isEmpty;
    $('input').each(function(){
      if($(this) === ""){
        var isEmpty = false;
        return isEmpty;
        alert(isEmpty);
      } else {
        var isEmpty = true;
        return isEmpty;
        alert(isEmpty);
      }
    });

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