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:
- input any name or string from the user
- prompt for the name of the user
- alert the message enter again when the user enters a null value
- alert the message bye when the user cancels the prompt
But when I test it and enter nothing it says hello – why?
3
Answers
From the docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
You used double
==
but its better to use===
.And
var
is also not recommendeda != null
is evaluating beforea == ""
.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.