简体   繁体   English

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

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

i have several input fields with a class name of required . 我有几个输入字段,其类名称为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 . 我下面有一个代码来检查我所有的<input>字段是否都有一个值,如果不为空或为null,它将显示/取消隐藏特定的div

but it doest seem to work on me. 但它似乎并没有对我起作用。

also, by default, #print is displayed as none via CSS. 同样,默认情况下,通过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();
    }
  });
});

I'd suggest: 我建议:

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

Simplified JS Fiddle demo . 简化的JS Fiddle演示

Obviously this should be run on submit , assuming you want to only show the #print element as a validation prior to submission. 显然,这应该在#print上运行,假设您只想在submit之前显示#print元素作为验证。

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 有点像这样的jFiddle

index.php 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 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);
});

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

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