【问题标题】:How to display an error message when the fields are not filled in javascript?javascript中未填写字段时如何显示错误消息?
【发布时间】:2019-05-16 15:49:18
【问题描述】:

当输入未填写时我们如何显示错误消息? 这是我的代码:

<body>
    <form method="post">
        <label>Enter your name</label>
        <input id="myName" type="text" placeholder="Your name here"><br>
        <label>enter your first name</label>
        <input id="myFirstName" type="text" placeholder="Your first name here"><br>
        <input id="myButton" type="button" value="submit">
       </form>
        <p id="mydisplay"></p>
    <script src="script.js"></script>
</body>

function myFunction(){
    var x = document.getElementById("myName").value + "<BR>" + document.getElementById("myFirtName").value ;
    if (x != ""){
        alert("Thank you fill in the fields")
    } else{
        document.getElementById("myDisplay").innerHTML = x;
    }
}

window.addEventListener("click", function () {
    document.getElementById("myButton").addEventListener("click", myFunction);
});

但我之前测试了这些字段,但没有显示错误消息告诉我我的输入为空。 另一方面,之后它很好地向我展示了我在我的页面输入中标记的内容

【问题讨论】:

  • 你总是将 + "
    " 添加到 x 所以逻辑上 x 总是 != ""
  • x 永远不会是空字符串,因为您已在其中附加了一个 br
  • 您的 JavaScript 中有一个错字:“myFirtName”而不是“myFirstName”(缺少“s”)
  • 我看到了三个问题。拼写错误“myFirtName”而不是“myFirstName”(缺少“s”)。您始终在字符串中添加 BR 的事实使得即使输入字段为空,它也永远不会为空,最后......表单被提交,因为您没有阻止默认行为。

标签: javascript html forms input


【解决方案1】:

试一试:

检查其中一个是否为空。

function myFunction(){
    if (!document.getElementById("myName").value || !document.getElementById("myFirstName").value){
        alert("Thank you fill in the fields")
    } else{
        document.getElementById("myDisplay").innerHTML = x;
    }
}

空白字符串在 JavaScript 中不是“真实的”。

参考:https://developer.mozilla.org/en-US/docs/Glossary/Truthy

【讨论】:

    【解决方案2】:

    如何使用所需的属性?会容易得多,试试吧..

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>The required Attribute</h2>
    <p>The required attribute specifies that an input field must be filled out before submitting the form.</p>
    
    <form action="/action_page.php">
      Username: <input type="text" name="usrname" required>
      <input type="submit">
    </form>
    
    <p><strong>Note:</strong> The required attribute of the input tag is not supported in Internet Explorer 9 and earlier versions, or in Safari prior version 10.1.</p>
    
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      • 1970-01-01
      相关资源
      最近更新 更多