+ 1
JavaScript Prompt when Cancled
Hey, I'm new to JS so this mighy be a dumb question but I'm getting an unexpect result when it comes to using the app and the prompt. The code below should alert the user they hit cancel with the word 'cancel'. If they hit 'okay' the code is to present the user with the text they entred. In actual use within the app when the user hits cancel, they are present with the text they've entred or varriable x. This seems to work in other browsers. Thanks in advance! var x = prompt ("a prompt","filler text"); if (x != null && x != '') { alert (x); //display what user entred } else { alert("cancel"); //display when the user cancels }
7 Antworten
+ 4
use !== instead of !=
double equals in JS checks for both type and value, basically never use == and != it gives unexpected results (unless u know what u doing) as JS is doing auto type coercion
to be on the safe side always use
=== and !== to compare stuff
+ 3
I tried:
let input = prompt()
if (input !== null && input !== ''){
alert(input)
} else {
alert("cancel")
}
works like a charm...
+ 2
Matt While null is a falsy value, it is not good practice to compare it to other falsy values. Both (null == "") and (null == false) return false, so a condition of (x != null || x != "") will still be met if x is null. Don't use the OR operator in this case.
I would recommend a shorter version that is.
if (!!x) {
// Do stuff
} else {
// Other stuff
}
+ 1
Because prompt doesn't return null in the app. You should change and to or operator.
In the app you can't really detect if it's cancelled because it returns empty string.
0
Even if i change the && to a || it still returns x not cancel
0
for clarification I'm on an iPhone.
Thanks everyone for the replys so far. deffiantly helpful!
So I narrowed down the problem. The problem exists because of the default text side of the prompt window (the "filler text" section in my above exmaple).
I've tried putting in the defualt text with the examples everyone gracely sent. I have not yet found an example where I can have the default text and correctly alert when the user cancels. Any thoughts?
- 1
I ran the code on mobile (latest webview v68) it's working as expected. Perhaps your android (and system webview) is old(less than 5.0).
Try adding another 'or' statement with the comparison to undefined, space; it may just work.
if (x != null || x != "" || x != undefined || x != " ")