admin管理员组

文章数量:1430368

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

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

Share Improve this question edited May 14, 2011 at 21:02 user113716 323k64 gold badges453 silver badges441 bronze badges asked May 14, 2011 at 20:58 ZADZAD 5692 gold badges7 silver badges23 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7
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/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

本文标签: javascriptHow to check how many empty input fields there areStack Overflow