0

Javascript validation is not working! Form is submitting even if function returns false. Where i should make changes? Here is the part of the code i wrote.

<html>
<head>
    <script>
    function check()
    {
        temp=document.getElementById("name").value;
        if(temp=="")
        {
            document.getElementById("err").innerHTML="error found";
            document.getElementById("name").focus();
            return false;
        }            
    }
    </script>
</head>
<body>        
    <form>
        <input type="text" id="name">
        <div id="err"></div>
        <input type="submit" onClick="check()">
    </form>
</body>
</html>
2
  • 6
    try onClick="return check()" Commented Mar 9, 2014 at 13:03
  • there are other ways to submit a form. don't attach to a button. use onSubmit. Commented Mar 9, 2014 at 13:06

1 Answer 1

4

I would suggest you to use onSubmit event of form instead of onClick event of button.

You also need to use return with HTML onevent attributes

HTML

<form onSubmit="return check()">
    <input type="text" id="name"/>
    <div id="err"></div>
    <input type="submit" />
</form>

DEMO

Sign up to request clarification or add additional context in comments.

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.