-1

This is a really simple problem. I had this working and then i must of changed something and now it doesn't work. Its just a peice of JS code checking for an empty string. Here is the code below. It's been driving me mad for 20 minutes trying to figure out what is wrong with this ridicliously simple code.

 <script  type="text/javascript">
 function validateForm(){
 var email= document.getElementById('email').value;
 if (email.length==''){
 alert("please fill out email");}}
    </script>

<form name="contact" method="post" action='ContactPHP.php'>
Your Email: <input name='email' type='text' /><br />
<input type="button" value="submit" onClick="validateForm()"/>
 </form>
1
  • 1
    It's easy to confuse name and id attributes. Make a habit of always putting both Commented Jul 27, 2011 at 20:40

6 Answers 6

3

Your javascript calls getElementById('email') but your input does not have an id of 'email'.

Assign an id to it.

<input name='email' id='email' type='text' />
Sign up to request clarification or add additional context in comments.

Comments

2

email.length does not return a string. You are comparing it to an empty string. Either use email == "" or email.length > 0.

Additionally, your input element has name "email", but you're looking for an element with id "email".

Here's the full (corrected) snippet:

<script  type="text/javascript">
    function validateForm(){
        var email= document.getElementById('email').value;
        if(email.value == '') {
            alert("please fill out email");
        }
    }
</script>

<form name="contact" method="post" action='ContactPHP.php'>
    Your Email: <input id='email' name='email' type='text' /><br />
    <input type="button" value="submit" onClick="validateForm()"/>
</form>

Comments

0

you have name='email' but are looking for the element with the ID of email...just add id='email' to your text input

Comments

0

Your input for the email does not have an Id="email"

Comments

0

You don't want to use document.getElementById here.

Try this:

function validateForm(form){ var email= form.email.value; if (email.length==''){ alert("please fill out email");}} Your Email:

Comments

0

I am too lazy to check but I have the impression that even if the validation fails the form will submit because the javascript function does not return false;

I woudl return false after the alert('yadda yadda'); and change the onclick event handler to:

onclick="return validateForm();"

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.