检查所有输入是否为空(没有值)

时间:2016-04-09 03:50:10

标签: javascript jquery return each

我只是想快速拼凑一些东西,检查我的表格中的任何输入是否为空 我正在尝试这个:

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

但它会一直警告 true 如果我这样做:

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

它会提醒我有的所有输入字段......
如果我有一个空输入,为什么它不返回false?

5 个答案:

答案 0 :(得分:2)

这是一个小片段,用于检查所有文字 inputs是否为空:

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

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

<强> jsBin playground

P.S:对于checkboxradio,游戏更简单:

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

BONUS::blank自定义选择器(适用于任何元素)

&#13;
&#13;
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
&#13;
*{margin:5px;padding:2px;}
&#13;
<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>
&#13;
&#13;
&#13;

<div><p>等标准元素上,:blank与jQuery&#39; :empty选择器的行为不同,因为请注意空格和换行符:

 <p>

 </p>

并查看结果:

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

回到你的问题:)

由于您循环所有元素,目前您只需将isEmpty的值设置为循环中的最后一个元素 - 价值 你可以将你的布尔标志声明为if,如:

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;
    }
});

另外,检查空虚执行=== ""更有意义返回true

否则反过来就是颠倒你的否定

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

以下是一个实例:

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

alert(isEmpty); // false
&#13;
<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="">
&#13;
&#13;
&#13;

答案 1 :(得分:1)

public class ResListProduct { @SerializedName("product") private List<Product> products; @SerializedName("group") private List<GroupProduct> groups; public ResListProduct() { } public List<Product> getProducts() { return products; } public List<GroupProduct> getGroups() { return groups; } } public class Product implements Serializable{ private static final long serialVersionUID = 6061052006970796100L; @SerializedName("id") private String idProduct; @SerializedName("group_id") private String groupId; @SerializedName("name") private String nameProduct; @SerializedName("price") private Price priceProduct; @SerializedName("images") private String urlImagesProduct; @SerializedName("sku") private String skuProduct; @SerializedName("names") private String names; // quantity for each product private int quantity; // title group product private String titleGroup; public Product(String titleGroup) { this.titleGroup = titleGroup; } public String getIdProduct() { return idProduct; } public String getGroupId() { return groupId; } public String getNameProduct() { return nameProduct; } public Price getPriceProduct() { return priceProduct; } public String getUrlImagesProduct() { return urlImagesProduct; } public String getSkuProduct() { return skuProduct; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getTitleGroup() { return titleGroup; } public String getNames() { return names; } public void setNames(String names) { this.names = names; } } public class GroupProduct { @SerializedName("category_id") public String groupId; @SerializedName("title") public String name; public String getName() { return name; } public GroupProduct() { } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } } public class Price implements Serializable { private static final long serialVersionUID = -3190011851589258858L; @SerializedName("USD") private double usd; @SerializedName("AUD") private double aud; @SerializedName("VND") private long vnd; // price checkout private String pricePayments; public Price() { } public double getUsd() { return usd; } public double getAud() { return aud; } public long getVnd() { return vnd; } public String getPricePayments() { return pricePayments; } public void setPricePayments(String pricePayments) { this.pricePayments = pricePayments; } } 在循环之外,所以它只会提示最终值。希望下面这段代码很有用

<强> HTML

alert

<强> JS

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

Chexk here for demo

答案 2 :(得分:0)

在您的代码中,您正在检查:

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

但是$(this)是一个jQuery对象,它永远不会与空字符串相同。也许你打算写这个?

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

首先尝试初始化变量,不包含任何值。然后在某个范围内放置一个值并调用它。

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