简体   繁体   中英

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.

Reference: 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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