3

The code below runs alert('Please enter your name!'); only when the user clicks Cancel on the prompt. I am trying to make the code also run said alert if the user doesn't input anything in the prompt box and clicks Enter. However, when they input nothing and click Enter, the code renders "Hello". How do I go about that?

var theName = prompt('What is your name?');

if(theName != null) {
   document.write('Hello, ' + theName);
}

else{
   alert('Please enter your name!');
}
1
  • 2
    RTM: If the user clicks OK without entering any text, an empty string is returned. Commented Aug 15, 2017 at 19:48

3 Answers 3

1

Return value from prompt:

String. If the user clicks "OK", the input value is returned. If the user clicks "cancel", null is returned. If the user clicks OK without entering any text, an empty string is returned.;

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

Comments

1

When the user clicks enter without entering any string the result will be "empty-string", so "". You are just checking for null. Empty-string is not null. So the code works as expected. You should check for null or "" instead. A shortcut would be to abuse javascript a bit and just check for

if (theName) { ...} else { ... }

without checking against null at all, since null and empty-string are both false-ish in javascript.

Comments

1

As @JohnnyMopp and Idos said, you'll get an empty string returned if the user clicks Enter without typing anything. You can check for that by adding another condition to your if statement:

var theName = prompt('What is your name?');

if(theName != null && theName != "") {
   document.write('Hello, ' + theName);
}

else{
   alert('Please enter your name!');
}

Comments

Your Answer

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