Reputation: 641
Why does this code say to fill in all values when all the fields are filled? It should only give the "fill in all fields" message when they are actually empty.
<html>
<head>
<title>javascript</title>
</head>
<body>
<h1>test page</h1>
<hr>
<script type="text/javascript">
function checkForm(form) {
for(var i = 0; i<form.elements.length; i++) {
if(form.elements[i].value == "") {
alert("Please fill out all fields.");
return false;
}
}
return true;
}
</script>
<form onSubmit="return checkForm(this)">
<input type="text" name="firstName"><br>
<input type="text" name="lastName">
<input type="submit">
</form>
</body>
</html>
Upvotes: 0
Views: 211
Reputation: 1638
You are also checking to make sure that the submit button is filled in. try this:
function checkForm(form) {
var win = true;
elements = form.elements;
for(var i = 0; i<elements.length; i++) {
if( elements[i].value == "" && elements[i].type != "submit") {
win = false;
}
}
if(!win){
alert("please fill out ALL fields!");
}
return win;
}
Upvotes: 0
Reputation: 207881
It's because your code is check every input field, in this case the submit button too. Change your function to this:
function checkForm(form) {
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].value == "" && form.elements[i].type != 'submit') {
alert("Fill out ALL fields.");
return false;
}
}
return true;
}
Upvotes: 0
Reputation: 14803
The submit button is a form element, and you haven't given it a value. As such, the JS loops through the inputs, gets to the submit button, finds no value, and raises the alert.
Try:
function checkForm(form) {
for(var i = 0; i<form.elements.length; i++) {
if(form.elements[i].type == "input" && form.elements[i].value == "") {
alert("Please fill out all fields.");
return false;
}
}
return true;
}
Upvotes: 1