0

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>

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

3 Comments

you probably don't want the "not submit" as this'll trip up if the form has checkboxes and/or radio buttons
@Mala - The form doesn't have those. If it did, I'd have coded for them. Just going by the OP's code. Thanks.
fair, but in my opinion it's better to have a function semantically match what it seems to do - otherwise you might as well just hardcode checks for elements[0] and [1], as that'd be shorter and slightly faster, and would still work with the provided code.
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.