Home > Mobile >  Javascript prompt issue
Javascript prompt issue

Time:04-13

So i'm doing a user input with prompt and i've done an if statement where if the prompt vas empty it would return alertbox with a warning. The problem is when i press ok on the alert. It puts me right in to the app. here is my code.

function getName(){
  var username = prompt("Write your username");
  if(username == ""){
    alert("Please write your username");
  }
  else{
    return username;
  }
}

CodePudding user response:

Please, you should use if (!username).

Because prompt can return undefined/null instead empty string.

CodePudding user response:

When I click "OK" at the prompt without entering any text, I do get an alert with "Please write your username", so that code does appear to be working.

It's worth noting that you are checking for an empty string, but you should also be checking for null.

When the user clicks the OK button, text entered in the input field is returned. If the user clicks OK without entering any text, an empty string is returned. If the user clicks the Cancel button, this function returns null.

https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt#return_value

You may also want to be aware the fact that some older versions of IE do return undefined, although I don't know anyone currently supporting IE.

Note that in Internet Explorer 7 and 8, if you do not provide this [default] parameter, the string "undefined" is the default value. https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt#parameters

You can check for truthiness in one expression with:

if(!username){
   // do stuff...
}

This will check for empty string, undefined, null, 0, false, and NaN.

See this post: What does this mean: if( variable ){ /* do something */ }

  • Related