Alamin
Alamin

Reputation: 3

I want to alert on click or keypress ( enter key ) when the input box is empty

I am using the below javascript to alert when the input box is empty.But when i press any key to write a word it alerts. I need to alert if only user press enter key when the field is empty.Can anyone tell me if there is any solution for this?

    <head>
        <meta charset="UTF-8">
        <title>Practise</title>
    </head>

    <body>
        <h1>Shopping List</h1>
        <p id="first">Get it done today</p>
        <input id="userinput" type="text" placeholder="Enter Your Items">
        <button id="enter">Enter</button>
        <ul>
            <li class="bold red" random="23">Notebook</li>
            <li>Hello</li>
            <li>Spanich</li>
            <li>Rich</li>
            <li>Poor</li>
            <li>Equal</li>
        </ul>


        <script>
            var button = document.getElementById("enter");
            var input = document.getElementById("userinput");
            var ul = document.querySelector("ul");

            function inputLength() {
                return input.value.length;
            }

            function alertEmpty() {
                if (inputLength() === 0) {
                    alert("Please Enter Your Item First");
                }
            }

            function creatListElement() {
                var li = document.createElement("li");
                li.appendChild(document.createTextNode(input.value));
                ul.appendChild(li);
                input.value = "";
            }

            function addListAfterClick() {
                if (inputLength() > 0) {
                    creatListElement();
                } else(alertEmpty());
            }

            function addListAfterKeypress() {
                if (inputLength() > 0 && event.keyCode === 13) {
                    creatListElement();
                } else(alertEmpty());
            }

            button.addEventListener("click", addListAfterClick);

            input.addEventListener("keypress", addListAfterKeypress);
        </script>
    </body></html>

Upvotes: 0

Views: 1208

Answers (2)

Farah Jokhio
Farah Jokhio

Reputation: 37

Modify alertEmpty function like this

function alertEmpty() {
   if( event.keyCode == 13 ){
      if (inputLength() === 0) {
         alert("Please Enter Your Item First");
      }
   }
}

Upvotes: 0

Shahzad
Shahzad

Reputation: 2063

It's just a logical problem in your addListAfterKeyPress(). You are checking if the length is more than 0 and also whether the enter key was pressed at the same time. You need to check for enter key first and the do the other checks:

function addListAfterKeypress() {
    if (event.keyCode === 13) {
        if (inputLength() > 0) {
            creatListElement();
        } else {
            alertEmpty() 
        }
    }
}

With this, the alert will only show if the enter key was pressed and the inputLength is 0

Upvotes: 1

Related Questions