简体   繁体   English

如何在javascript中填写字段时显示错误消息?

[英]How to display an error message when the fields are not filled in javascript?

how do we display an error message when input are not filled? 如何在未填写输入时显示错误消息? here is my code: 这是我的代码:

<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);
});

yet I test the fields before but no error message is displayed to tell me that my input are empty. 但我之前测试了字段,但没有显示错误消息告诉我输入为空。 on the other hand after that it shows me well what I mark in the input in the my page 另一方面,它显示了我在我的页面输入中标记的内容

Give this a go: 放手一搏:

Checks to see if either is blank. 检查是否为空白。

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

Blank strings are not "truthy" in JavaScript. 空格字符串在JavaScript中不是“真理”。

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

What about using The required Attribute? 那么使用必需的属性呢? would be much easier, git it a try.. 会更容易,试试吧..

 <!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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM