JavaScript Prompt when Cancled | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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 }

27th Jul 2018, 1:07 PM
Matt
7 Answers
+ 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
27th Jul 2018, 1:54 PM
damyco
damyco - avatar
+ 3
I tried: let input = prompt() if (input !== null && input !== ''){ alert(input) } else { alert("cancel") } works like a charm...
27th Jul 2018, 1:58 PM
damyco
damyco - avatar
+ 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 }
27th Jul 2018, 2:02 PM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar
+ 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.
27th Jul 2018, 1:30 PM
Toni Isotalo
Toni Isotalo - avatar
0
Even if i change the && to a || it still returns x not cancel
27th Jul 2018, 1:43 PM
Matt
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?
27th Jul 2018, 6:47 PM
Matt
- 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 != " ")
27th Jul 2018, 1:57 PM
Lord Krishna
Lord Krishna - avatar