Elli Raynai
Elli Raynai

Reputation: 21

Check If User Input Is Empty

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

Upvotes: 2

Views: 5993

Answers (3)

steven sasidharan
steven sasidharan

Reputation: 11

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

**JS** 
let inputEl = document.querySelector('input') 

let h1 = document.querySelector('h1') 
inputEl.addEventListener('input',()=>{ 
  h1.innerText = "Welcome, " + inputEl.value 
 if (inputEl.value.length === 0) h1.innerText = "Enter Your Username";
})

Upvotes: 1

ATP
ATP

Reputation: 3249

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

Upvotes: 3

Rob Sutcliffe
Rob Sutcliffe

Reputation: 361

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

Upvotes: 1

Related Questions