开发者

How to check how many empty input fields there are?

I've about 5 input fields and before checking them I want to be able to alert using javascript to let the user know that there are empty fields which must be filled in before checking.

So I want to be able to alert using js if 2 of the 5 inpu开发者_运维问答t fields are empty!

Can anybody please help me with this! I've research a lot and read some blogs that saying to use the "length" but couldn't figure it out!

So as soon as the user clicks on the submit button with the id of "submit", an alert would prompt saying must fill in at least 2 out of the 5 input boxes...

Here is my code:

<input type="text" id="a" value="" />
<input type="text" id="b" value="" />
<input type="text" id="c" value="" />
<input type="text" id="d" value="" />
<input type="text" id="e" value="" />

<input type="submit" id="submit" value="Check Form" />

Thanks


document.getElementById('submit').onclick = function() {
    var inputs = document.getElementsByTagName('input'),
        empty = 0;

    for (var i = 0, len = inputs.length - 1; i < len; i++) {
        empty += !inputs[i].value;
    }
    if (empty > 3) {
        alert('You must fill in at least 2 fields');
    }
};

Example: http://jsfiddle.net/Fn8cw/


With jquery you can loop through all of your input fields and increment a variable if the input field is empty:

$("#your_form_div").change(function(){     
$(this).parents('form')             
.find(':input').each(function(i) {
if( $(this).val() )
//here your incremented variable
}); }); 


this will tell you how many are empty

var empty = $('input:text').filter(function() { return $(this).val() == ""; });

 if (empty.length > 3){
    alert("you must fill in at least two inputs");
}

here is a working demo

of course I'm assumming you can use jQuery

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜