简体   繁体   中英

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM