skip to Main Content

How can I get the prompt to detect the null value in javascript?

I tried this but entering ok will return a "Hello" instead of "Enter again".

function myprompt() {
  var a = prompt("Enter your name", "abc");
  if (a != null) {
    document.getElementById("para").innerHTML = "Hello " + a;
  } else if (a == "") {
    document.write("Enter again");
  } else {
    document.write("BYE...")
  }
}
myprompt()
<p id="para"></p>

I’m making a JavaScript project and I want to alert when the user enters nothing in the prompt

What it’s supposed to do:

  1. input any name or string from the user
  2. prompt for the name of the user
  3. alert the message enter again when the user enters a null value
  4. alert the message bye when the user cancels the prompt

But when I test it and enter nothing it says hello – why?

3

Answers


  1. From the docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt

    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.

    function myPrompt() {
        var a = prompt("Enter your name", "John Doe");
        if (a == null) {
            document.write = "User have cancelled the prompt!";
        } else if (a == "") {
            document.write("User haven't entered anything and clicked OK");
        } else {
            document.write("User have entered a valid text")
        }
    }
    
    Login or Signup to reply.
  2. function myprompt() {
      const a = prompt("Enter your name", "abc");
      if (a === null) {
        console.log("canceled");
        document.write("BYE...");
      } else if (a === "") {
        console.log("enter again");
        document.write("Enter again");
      } else {
        console.log("Hello " + a);
        document.getElementById("para").innerHTML = "Hello " + a;
      }
    }

    You used double == but its better to use ===.
    And var is also not recommended

    Login or Signup to reply.
  3. a != null is evaluating before a == "". a == "" means a is not null, so you will never reach that part of the if condition. You need to invert your conditions.

    start with a null check, then empty string, then non-empty string, not the other way around.

    function myprompt() {
      var a = prompt("Enter your name", "abc");
      if (a == null) {
        document.write("BYE...");
      } else if (a == "") {
        document.write("Enter again");
      } else {
        document.getElementById("para").innerHTML = "Hello " + a;
      }
    }
    myprompt()
    <p id="para"></p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search