【问题标题】:Javascript onclick with if statement [duplicate]带有if语句的Javascript onclick [重复]
【发布时间】:2020-05-01 16:22:38
【问题描述】:

大家好,我真的是 JavaScript 新手,
如果用户按下检查,我希望出现一条警报消息,
看看输入是对还是错,
而且我已经尝试了很长时间,但无论如何它都不起作用,它只是一个简单的代码。

我真的为此苦恼了好几个小时,试图弄清楚为什么当我按下检查按钮时没有出现警报消息。

非常感谢任何帮助或任何提示,非常感谢!

function myFunction() {
  var x = document.getElementById("f").value;
  var z = document.getElementById("s").value;
  var c = document.getElementById("e").value;
  var v = document.getElementById("p").value;
  var b = document.getElementById("p1").value;

  if (isNaN(x) || x = "") {
    alert("First Name input is wrong");
  } else {
    alert("Input is ok");
  }


  if (isNaN(z) || z = "") {
    alert("Second Name input is wrong");
  } else {
    alert("Input is ok");
  }

  if (isNaN(c) || c = "") {
    alert("Email input is wrong");
  } else {
    alert("Input is ok");
  }

  if (v = "") {
    alert("Input is wrong");
  } else {
    alert("Input is ok");
  }

  if (b = "" || b !== v) {
    alert("Password does not match");
    else {
      alert("Input is ok");
    }
  }
}
<div class="event">
  <h1> Event Planning</h1>
</div>
<div class="back">

  <table border="1">
    <form action="submit.php" method="post">
      <tr>
        <th colspan="2"> Sign UP</th>
      </tr>
      <tr>
        <td> First Name </td>
        <td> <input type="text" name="FirstName" id="f"></td>
      </tr>
      <tr>
        <td> Second Name</td>
        <td> <input type="text" name="SecondName" id="s"></td>
      </tr>
      <tr>
        <td> Email Address</td>
        <td> <input type="email" name="email" id="e"> </td>
      </tr>
      <tr>
        <td> Password</td>
        <td> <input type="password" name="psd" id="p"> </td>
      </tr>
      <tr>
        <td> Repeat Password</td>
        <td> <input type="password" name="psd2" id="p1"> </td>
      </tr>
      <tr>
        <td colspan="2"> <input type="submit" name="submit" value="submit">
          <button type="button" id="but" onclick="myFunction()">Check</button></td>
      </tr>
    </form>
  </table>

【问题讨论】:

  • 一个等号赋值,两个比较。你正在寻找if (variable == thing)。
  • 还是不行

标签: javascript


【解决方案1】:

您的函数中有一些语法错误。

Javascript 需要 ==(或 ===)进行比较。

还需要在“密码不匹配”后的else前加一个大括号},在后面的“输入正常”后去掉一个。

【讨论】:

  • OP 的附加说明,您可以使用 Chrome 或 Firefox Developer Console 等工具轻松找到此问题。建议检查一下。它会给你很多时间。此外,您可能会考虑获得更好的 IDE - 现代 IDE 会实时告诉您您所犯的错误。
猜你喜欢
  • 2016-07-11
  • 2016-07-25
  • 1970-01-01
  • 2016-01-30
  • 2019-10-08
  • 1970-01-01
  • 1970-01-01
  • 2015-03-01
  • 2013-08-08
相关资源
最近更新 更多