Check If User Input Is Empty

Viewed 1913

I'm having some trouble checking whether the input field is empty and when it is I want to revert it to the content in the h1 tag.

<body>
    <h1>Enter Your Username</h1>
    <input type="text" id="username" />
  </body>

const input = document.querySelector("input");
const h1 = document.querySelector("h1");

input.addEventListener("input", (e) => {
  h1.innerText = `Welcome ${input.value}`;
});

if (input.length === 0) {
  h1.innerText = "Enter Your Username";
}`enter code here`
2 Answers

input has not length property. You probably meant:

if (input.value.length === 0) {
  h1.innerText = "Enter Your Username";
}

or without whitespaces: (thanks to Roko)

if (input.value.trim().length === 0) {
      h1.innerText = "Enter Your Username";
    }

Currently the input length check is not inside the event handler. Ideally you want to check if the input is empty every time the input value changes. So you want it inside your input.addEventListener callback

input.addEventListener("input", function(e) {
  h1.innerText = this.value.length === 0 ?
    "Enter Your Username" :
    `Welcome ${input.value}`; 
});
Related