0

How can I detect if the text input entered by the user is empty or contain some text?

I am currently making a TO-DO app and I want that if a user does not type anything in the text area and click add, the app should not take any input and display a message like Enter Valid Items or similar.

Any help will be appreciated :)

Sanyam
  • 64
  • 3
  • 11
  • 2
    If it's a text field the retrieved value should be an empty string by default. So you can just check the `length` property and assert that it's greater than 0. – Adam Feb 01 '19 at 17:55
  • I figured out that I can use `requried` in the input as a field. – Sanyam Feb 02 '19 at 06:27

2 Answers2

0

Just check for the string length with the .length property.

something like:

if (your_var.length > 0) {
    // ok
    alert("Ok");
} else {
    alert("Enter Valid Items");
}

See https://www.w3schools.com/jsref/jsref_length_string.asp

Luca Angioloni
  • 2,243
  • 2
  • 19
  • 28
0

//querySelectorAll get all input element.

document.querySelectorAll('input').forEach(input=>{
  //Adding an event listener to all inputs which is be fired when the input 
  //field will be defocused
  input.addEventListener('blur',(e)=>{
    //check if the input which is defocused is empty.
    if(e.target.value === ''){
       //Set error as placeholder
       e.target.setAttribute('placeholder',"This field is required")
    }
    else console.log("Input field not empty")
  })
})
<input type="text">
<input type="text">
<input type="text">
<input type="text" placeholder="text">
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73