简体   繁体   English

jQuery检查至少五个输入中是否包含数据

[英]jQuery check that at least five inputs have data in them

I have a number of inputs on the page and need to force that at least 5 items have been filled. 我在页面上有很多输入,需要强制至少填写5个项目。 And if not then show a message saying you must fill at least 5. So far I have tried the following but it just shows the error over and over again. 如果没有,则显示一条消息,提示您必须至少填充5个。到目前为止,我已经尝试了以下操作,但它一次又一次地显示错误。 What's the proper way of doing this? 这样做的正确方法是什么?

$('div.inputs input').each(function(i) {
    $input = $(this);
    while (i < 5) {
        if ($($input).val() == '') {
            alert('must fill at least 5 items!');
        }
    }
});​

You can create a better selector, and then: 您可以创建一个更好的选择器,然后:

 
 
 
  
  if ($('div.inputs input[value!=""]').length < 5) { alert('must fill at least 5 items!'); }
 
  

Explanation: 说明:

The div.inputs input[value!=""] selector selects all input fields which has something in the value attribute, and then you can fetch the length of the selected items. div.inputs input[value!=""]选择器选择在 value属性中包含某些内容的所有输入字段,然后可以获取所选项目的长度。

The previous solution works (somehow), but I recommend a better one: 先前的解决方案有效(某种程度上),但我建议一个更好的解决方案:

 if ($('div.inputs input').filter(function () { return $(this).val().length > 0; }).length < 5) { alert('must fill at least 5 items!'); } 

The methods shown in KARASZI István's answer are neater, but as far as explaining what is wrong with your code and how you might fix it, the (main) problem is that the while condition: KARASZIIstván的答案中显示的方法比较整洁,但是就解释代码有什么问题以及如何解决它而言,(主要)问题是while条件:

while(i<5)

...is evaluating a variable, i , that is not changed by the contents of the loop. ...正在评估变量i ,该变量不会被循环的内容更改。 On the first iteration of the .each() loop i is 0 so the while condition is true and remains true so you get an endless loop. .each()循环的第一次迭代中, i为0,因此while条件为true 并保持为true,因此您将获得一个无限循环。

To keep the general structure of your code and loop through each input testing the values you could do something like this: 为了保持代码的一般结构并遍历每个输入测试值,您可以执行以下操作:

var filled = 0;

$('div.inputs input').each(function (i) {
    if (this.value != '') {
        filled++;
        if (filled === 5)
           return false;
    }
});

if (filled < 5) {
    alert('must fill at least 5 items!');
}

That is, for each input that is not blank increment a counter, and then check the counter after the loop. 也就是说,对于每个非空白的输入,增加一个计数器,然后在循环后检查该计数器。 Note that returning false from within the .each() callback function stops the .each() loop immediately; 请注意,从.each()回调函数内部返回false立即停止.each()循环; no need to keep counting once we've reached the minimum 5 non-empty values. 达到最低5个非空值后,无需继续计数。

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

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