简体   繁体   English

如何检查所有输入框是否为空或等于0?

[英]How to check all input boxes are not empty or equal to 0?

I have a form with many input boxes. 我有一个包含许多输入框的表单。 I want to make a function that will go through each box and determine if any of the boxes are 0 or empty. 我想创建一个函数,它将遍历每个框并确定任何框是0还是空。

The user only needs to fill one one of the input boxes. 用户只需填写其中一个输入框。 If they fill all of them, that is fine too. 如果他们填满所有这些,那也没关系。 But one is the minimum requirement. 但一个是最低要求。 Otherwise an error alert should appear. 否则,将出现错误警报。

<form method="POST" onsubmit="return checkInputs()" name="inputData" id="inputData">

  Socks <input class="text-center" value="0" type="text" id="socks" name="socks">

  Underwear <input class="text-center" value="0" type="text" id="underwear" name="underwear">

  Ties <input class="text-center" value="0" type="text" id="ties" name="ties">

  Pants <input class="text-center" value="0" type="text" id="pants" name="pants">


  <a href="#" onClick="checkInputs()"> Save</a>

</form>

And my JS 而我的JS

function checkInputs() {

    var flag=0;

    $("form#inputData :input[type=text]").each(function(){
        var input = $(this); 
        if(input.val() > 0) {
          // all good
        } else { 
            flag=1; 
        }
    });

    if(flag==1){
        alert('Error!');
    } else {
        alert('Thanks!');
    }

}

My codePen is http://codepen.io/anon/pen/mPmoma 我的codePen是http://codepen.io/anon/pen/mPmoma

try something like this: 尝试这样的事情:

function checkInputs() {

    var flag=0;
  var result = new Array();

    $("form#inputData :input[type=text]").each(function(){
        var input = $(this); 
        if(input.val() > 0 && input.val() !== '' ) {
            result.push(input.val());
        } 
    });

    if(result.length > 0){
        alert('thanks')
    } else {
        alert('error!'); 
    }

}

for simpler code, you can also use jquery selectors: 对于更简单的代码,您还可以使用jquery选择器:

$('input[type=text]:not([value=""],[value=0])')

*Edit: with a conditional: *编辑:带条件:

var len = $('input[type=text]:not([value=""],[value=0])').length;
if(len>0) alert('thanks');
else alert('error!');

As pointed out by the other answers, the critical flaw in your design is that the $('.alert-danger') is modified for each iteration of .each() . 正如其他答案所指出的,设计中的关键缺陷是每次迭代的.each()都会修改$('.alert-danger') .each() Below is one possible solution with the explanation to follow: 以下是一个可能的解决方案,其解释如下:

 function checkInputs() { $('.alert-danger').show(); $("form#inputData :input[type=text]").each(function() { var input = $(this); if (parseInt(input.val(), 10) > 0) { $('.alert-danger').hide(); return false; } }); if($('.alert-danger').is(':visible')) { alert("Danger!"); } else { alert("Thanks!"); } } 
 body { padding: 0; margin: 0; } .alert-danger { color: #a94442; background: #f2dede; border-bottom: 1px solid #ebccd1; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="POST" onsubmit="return checkInputs()" name="inputData" id="inputData"> <div style="display:none" class="alert-danger">You need enter at least 1 quantity for any or all of these choices. </div> <br /><br /> <input class="text-center" value="0" type="text" id="socks" name="socks"><br /> <input class="text-center" value="0" type="text" id="underwear" name="underwear"><br /> <input class="text-center" value="0" type="text" id="ties" name="ties"><br /> <input class="text-center" value="0" type="text" id="ties" name="ties"><br /> <br /><br /> <a href="#" onClick="checkInputs()"> Save</a> </form> 

You'll notice a few changes in the above code example from the one you provided. 您会注意到上面代码示例中的一些更改来自您提供的代码示例。 First, I removed the flag variable. 首先,我删除了flag变量。 By calling .show() and .hide() at the appropriate times, we can utilize the .alert-danger 's visibile presence as the key as to whether or not we show the error or hide the error. 通过调用.show().hide()在适当的时候,我们可以利用.alert-danger的存在看得到的关键,我们是否或不显示错误或隐藏的错误。

The second change is that we're parsing the input box values using parseInt(input.val(), 10) before checking to see if the value is greater than 0 . 第二个变化是我们在检查值是否大于0之前使用parseInt(input.val(), 10)解析输入框值。 By using the type conversion properties that parseInt() provides, we can filter out irrelevant content. 通过使用parseInt()提供的类型转换属性,我们可以过滤掉不相关的内容。 For example the letter "a" will not validate as a legitimate value since its non numeric since parseInt("a", 10) = NaN and NaN > 0 . 例如,字母"a"将不会验证为合法值,因为它是非数字的,因为parseInt("a", 10) = NaNNaN > 0

Finally, since you noted that only one value had to be set for validation to accept the input, I've added return false; 最后,既然你注意到只有一个值必须设置为验证才能接受输入,我添加了return false; to the .each() loop. .each()循环。 With this line, the loop will short circuit as soon as one value validates correctly. 使用此行,只要一个值正确验证,循环就会短路

The first issue has been clearly explained by others - iteration. 其他人已经清楚地解释了第一个问题 - 迭代。

The second issue . 第二个问题 You're using a link to trigger the function. 您正在使用链接来触发该功能。 Do not forget that the default action of a link is to follow the link, even if it is to the same page or '#' in your case, which may cause the page to reload. 不要忘记链接的默认操作是跟随链接,即使它是相同的页面或您的情况下的'#' ,这可能导致页面重新加载。 Use event.preventDefault(); 使用event.preventDefault(); to prevent the default action. 防止默认操作。

Thirdly , the alert() function s not a good debugging tool. 第三alert()函数不是一个好的调试工具。 The page refreshes as soon as you click ok on the alert and the page resets. 一旦您在警报上单击“确定”并且页面重置,页面就会刷新。

 $('.save').on('click', function(e) { e.preventDefault() var ok = $(this).closest('form').find(':text.text-center').filter(function() { return $(this).val() > 0; }); if( ok.length ) { $('.alert-danger').slideUp(); $('.out').text('Thanks!'); } else { $('.alert-danger').slideDown(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="POST" name="inputData" id="inputData"> <div style="display:none" class="alert-danger">You need enter at least 1 quantity for any or all of these choices. </div> <br /><br /> <input class="text-center" value="0" type="text" id="socks" name="socks"><br /> <input class="text-center" value="0" type="text" id="underwear" name="underwear"><br /> <input class="text-center" value="0" type="text" id="ties" name="ties"><br /> <input class="text-center" value="0" type="text" id="ties" name="ties"><br /> <br /><br /> <a href="#" class="save"> Save</a> <div class="out"></div> </form> 

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

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