Darshn
Darshn

Reputation: 1601

Form is submitting even if javascript function return false

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>

Upvotes: 0

Views: 2729

Answers (1)

Satpal
Satpal

Reputation: 133403

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

Upvotes: 4

Related Questions