views:

83

answers:

4

I'm trying to validate a form, but doesn't work :\ , When I submit the form goes to mail.php even if the required fields are missing, but I set onsubmit to validate() so it should check, but doesn't work. What's the problem with my code? I can't find it.

HTML:

<form action="mail.php" onsubmit="return validate()" method="post" class="contact-form" id="contactForm">

    <div id="errors"></div>

    <label for="author">Name:</label><br/><br/>

    <input type="text" name="author" id="message" /><br/><br/>

    <label for="author">Message:</label><br/><br/>

    <textarea name="message" id="message"></textarea><br/><br/>

    <input type="submit" class="button" value="Send Message"/>

</form>

Javascript:

    <script type="text/javascript">
    function error(message){
        return "<p class=\"error\">"+message+"</p>";
    }

    function validate(){
        var form     = document.getElementById("contactForm");
        var author     = document.getElementById("author");
        var message = document.getElementById("messsage");
        var errors    = document.getElementById("errors");
        alert(author.value);
        if(message.value == '' || author.value == ''){
            errors.innerHTML = error("Please fill in all fields.");
            return false;
        } else {
            return true;
        }

    }
</script>
+3  A: 

id=author on your first input element.

Also check out jQuery it will save you time in the long run

NimChimpsky
+3  A: 

You have two elements with the id message and none with author.

The Markup Validator would have picked this up for you.

David Dorward
+2  A: 
var message = document.getElementById("messsage");

message has an extra "s".

<input type="text" name="author" id="message" />

You need to change "message" to "author"

mcrumley
Hey! Thanks I fixed it, however still doesn't works :O
CIRK
It worked for me here: http://jsfiddle.net/5wTY6/
mcrumley
Hmm thanks! I fixed it, the problem was with the `s` :D sry
CIRK
+1  A: 

This is wrong:

<input type="text" name="author" id="message" />

Need to set name and id to the same values (you're using id="message" for the next field, so there's a clash.

Also both your label tags have for="author"; the second one is wrong.

I guess your problem here is too much copy+paste. ;)

Spudley
You don't need to set `name` and `id` to the same value (in fact, when dealing with radio groups — you can't, since then you must have multiple elements with the same name)
David Dorward