Javascript检查表单onsubmit

时间:2015-09-02 03:08:10

标签: javascript html

我已使用event.preventDefault()停止form操作并致电login(),但当login函数返回true时,仍然不能做表单操作吗?

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>

1 个答案:

答案 0 :(得分:4)

event.preventDefault();移除onsubmit。无论从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>