简体   繁体   中英

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. 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. 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.

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:

while(i<5)

...is evaluating a variable, i , that is not changed by the contents of the loop. 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.

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; no need to keep counting once we've reached the minimum 5 non-empty values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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