0

Here, I want the function to trigger only if i have typed something in the input field. If it's empty I want to alert that it can't be empty. I tried if else condition but it doesn't help. I even tried using typeof but no matter what the type is string.

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


function myFunc(){
let name = input.value;
if(name==null){
alert("PLEASE ENTER YOUR NAME")
} else{
alert('Hello'+' '+name);
}
};
<body>
 
  
  <input placeholder="Enter your name" id="input">
  <button id="btn" onclick="myFunc()">Click me!</button>
  
</body>

3 Answers 3

2

input.value is not null when the input is empty, its just empty string.
try this:

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

function myFunc() {
  let name = input.value;
  if (name == "") {
    alert("PLEASE ENTER YOUR NAME")
  } else {
    alert('Hello' + ' ' + name);
  }
};
<body>
  <input placeholder="Enter your name" id="input">
  <button id="btn" onclick="myFunc()">Click me!</button>
</body>

Sign up to request clarification or add additional context in comments.

Comments

0

You have to check for empty string as well. In practice, you are never going to get a null value for input.value but it's not bad to program conservatively

function myFunc(){
let name = input.value;
if(name==null || name.length == 0){
alert("PLEASE ENTER YOUR NAME")
} else{
alert('Hello'+' '+name);
}
};

or you can take advantage of how awesomely Javascript implements the not (!) operator and just do:

function myFunc(){
let name = input.value;
if(!name){
alert("PLEASE ENTER YOUR NAME")
} else{
alert('Hello'+' '+name);
}
};

Comments

0

You need to test for empty/space and it is not recommended to have inline event handlers

document.getElementById("btn").addEventListener("click", function() {
  const input = document.getElementById("input");
  const name = input.value.trim();
  alert(name ? 'Hello ' + name : 'Please enter your name')
});
<input placeholder="Enter your name" id="input">
<button type="button" id="btn">Click me!</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.