Simple username prompt using JS not functioning correctly

Viewed 358

I am making a very simple JavaScript username prompt, which, at the press of a button, requests that the user enters a username. After the user enters a name, the code writes a simple greeting with the user's username. However, if they leave it blank there is an alert which states the username cannot be blank.

The button works and the prompt comes up, but when you enter a blank username, the error doesn't come up.

I have tried to replace the null with undefined, but when I do that, any entry, including no entry of username, always brings up the error.

I cannot figure out what is wrong with my code below:

function usernametest() {
  let username = prompt("Enter a username");

  if (username != null) {
    document.write("Hello " + username + "! How are you today?");
  } else {
    alert("Username cannot be blank!");
  }
}
<input type="button" value="Click to test username prompt" onclick="usernametest();">

3 Answers

You should be checking against an empty string.

if (username != '')

If you want to make to make sure that the username is not only whitespace, you can use .trim(). See also my answer here.

if(username.trim())

Check against empty string too

if (username != null && username != '') {
    document.write("Hello " + username + "! How are you today?");
} 

function usernametest() {

let username = prompt("Enter a username");

if (username != '') {
    document.getElementById('text').innerHTML ="Hello " + username + "! How are you today?";
    } 
else {
    alert("Username cannot be blank!");
}
}
<input type="button" value="Click to test username prompt" onclick="usernametest();">
<div id='text'><div>

Related