繁体   English   中英

检查所有输入字段是否具有值jQuery条件

[英]check if all input field has value jQuery condition

我有几个输入字段,其类名称为required

我下面有一个代码来检查我所有的<input>字段是否都有一个值,如果不为空或为null,它将显示/取消隐藏特定的div

但它似乎并没有对我起作用。

同样,默认情况下,通过CSS, #print显示为none。

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

我建议:

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

简化的JS Fiddle演示

显然,这应该在#print上运行,假设您只想在submit之前显示#print元素作为验证。

参考文献:

正如我在上面的评论中所述,在用户加载任何内容之前,您正在检查页面加载时的值。 如果页面上有一个按钮,请将事件绑定到将在适当的时间触发该功能的事件。

有点像这样的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();   
    }
});

尝试

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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