Make Enter / Return键提交表格并执行功能

时间:2017-12-01 23:52:17

标签: javascript html

我正在为我的网站开发一个简单的表单验证系统 - Login()函数 - 并希望允许用户只需按Enter即可提交表单。但是,我有两个单独的表单 - 都使用相同的标记属性 - 但是一个和另一个没有。怎么了?

工作代码:



function Login() {

  var id = document.login.id.value;

  location.href = "users/" + id + ".html"

}

<form name="login" method="get" onsubmit="return Login();">
  <input type="password" maxlength="7" name="id" id="id" placeholder="Session ID">
  <br />
  <input type="button" value="Join" onClick="Login()">
  <a href="index.html"><button>Cancel</button></a>
</form>
&#13;
&#13;
&#13;


破码:

&#13;
&#13;
function Login() {
  var done = 0;
  var username = document.login.username.value;
  username = username.toLowerCase();
  var password = document.login.password.value;

  if (username == "user1" && password == "password1") {
    window.location = "../account/user1/index.html";
    done = 1;
  }

  if (username == "user2" && password == "password2") {
    window.location = "../account/user2/index.html";
    done = 1;
  }
  if (username == "user3" && password == "password3") {
    window.location = "../account/user3/index.html";
    done = 1;
  }

  if (done == 0) {
    alert("Incorrect username/password.")
  }
}
&#13;
<form name="login" method="get" onsubmit="return Login();">
  Username:<input type="text" name="username">
  <br /> Password:
  <input type="password" name="password">
  <br />
  <br />
  <input type="button" value="Login" onClick="Login()">
  <input type="reset" value="Cancel" />
</form>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

要确保您使用的浏览器或网络客户端知道按下提交的按钮,您应该使用:

<input type="submit" value="Login" onClick="Login()">

而不是

<input type="button" value="Login" onClick="Login()">

(注意类型属性的区别)。