JavaScript密码函数输出错误数据

t3psigkw  于 2022-12-17  发布在  Java
关注(0)|答案(2)|浏览(126)

更新版本:
新版本看起来像这样,但仍然不工作,任何修复

var pw = "1234";

function checkpw(event, input) {
  var x = document.getElementById("pw").value;
  
  if (x.value === "") {
    alert("no password entered");
  } else if (x.value !== pw) {
    alert("wrong password");
  } else {
    alert("correct pw");
  }
}
<html>

<head>
  <title>Hello</title>
</head>

<body>
  <input type="password" id="pw" oninput="">
  <button type="submit" onclick="checkpw(event, this)">submit</button>
</body>

</html>

上面的代码仍然只输出错误的密码。

bq8i3lrv

bq8i3lrv1#

您需要访问输入字段的value以获取要比较的适当文本值。此外,您的逻辑应该先检查空值,然后检查错误。

var pw = "1234";

function checkpw(event, input) {
  var x = document.getElementById("pw"); // could be `input` instead
  
  if (x.value === "") {
    console.log("no password entered");
  } else if (x.value !== pw) {
    console.log("wrong password");
  } else {
    console.log("correct pw");
  }
}
<input type="password" id="pw" oninput="checkpw(event, this)">

我建议将字段 Package 在窗体中。

**注意:**切勿在客户端上执行身份验证。

一个二个一个一个

mtb9vblg

mtb9vblg2#

function checkpw() {
  var x = document.getElementById("pw");
  var pw = "1234";
  if (x.value == pw) {
  //--------^ the variable x refers to the element itself. x.value is what you are looking for
      alert("correct pw");
  } else if(x.value == "") {
  //--------^ pw equals to "1234" which is the variable you created. replace pw with x.value instead (consider doing x.value.trim())
      alert("no password entered");
  } else {
      alert("wrong password");
  }
}
<input type="password" id="pw" />
<!---------------------^ I've added an id attribute since your code uses getElementById and that requires an id --->
<button onclick="checkpw()">Check password</button>

相关问题