user8468882
user8468882

Reputation:

JavaScript Prompt() input

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!');
}

Upvotes: 3

Views: 117

Answers (3)

freginold
freginold

Reputation: 3956

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!');
}

Upvotes: 1

Patrick Kelleter
Patrick Kelleter

Reputation: 2771

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.

Upvotes: 1

Idos
Idos

Reputation: 15310

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.;

Upvotes: 1

Related Questions