简体   繁体   中英

Javascript check form onsubmit

I've used event.preventDefault() to stop the form action and call the login() , but when the login function return true , it still can't do the form action?

HTML:

<form onsubmit="event.preventDefault();return login();" action="index.php" method="get" id="register-form" >

Javascript:

<script type="text/javascript">
function login() {

    var password = window.prompt("Please input password", "");
    if (password !== '123') {
        alert('Password is incorrect');
        return false;
    } else {
        alert('Success');
        return true;
    }
}
</script>

Remove event.preventDefault(); from the onsubmit . This will stop the form submission regardless of the value returned from login() .

Demo

 function login() { var password = window.prompt("Please input password", ""); if (password !== '123') { alert('Password is incorrect'); return false; } else { alert('Success'); return true; } } 
 <form onsubmit="return login();" action="index.php" method="get" id="register-form"> <input type="submit" value="Login" /> </form> 

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