简体   繁体   中英

show alert when textbox input is empty

I want to show an alert when the text box input of the first name is empty.

Javascript Code

<script>
    function validation() {
        var fname = document.getElementByID("fname").value;
        if ( fname== "")
            alert("Enter First Name");
    }
</script>

HTML Code

    <form>
        First name:
        <input type="text" id="fname">
        <br/><br/>
        <button id="btnSubmit" onclick="validation()">Submit</button>
        <button id="btnReset">Reset</button><br/>
        <button id="btnMenue"><a href= "index.php">Menue</a></button>
    </form>

I have tried related articles but they didn't solve my problem.

Two issues in your code:

  1. getElementByID should be getElementById
  2. You need to capture the event object and call preventDefault on it to stop the default behaviour that is stop form submission.

 function validation(e) { var fname = document.getElementById("fname").value; // Typo here ID should be Id. if (fname == "") { e.preventDefault(); alert("Enter First Name"); } }
 <form> First name: <input type="text" id="fname"><br/><br/> <button id="btnSubmit" onClick="validation(event)">Submit</button> <button id="btnReset">Reset</button><br/> <button id="btnMenue"><a href= "index.php">Menue</a></button> </form>

document.getElementByID is not a function , you have a type in your code:

getElementByID <- last letter is big in you code, should be small getElementById

working example

 function validation() { // big D, throws error // var fname = document.getElementByID("fname").value; var fname = document.getElementById("fname").value; console.log(fname); if (fname == "") alert("Enter First Name"); }
 <form> First name: <input type="text" id="fname"><br/><br/> <button id="btnSubmit" onclick="validation()">Submit</button> <button id="btnReset">Reset</button><br/> <button id="btnMenue"><a href= "index.php">Menue</a></button> </form>

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