I'm calling a Javascript window.prompt()
and prompting the user to submit a variable which I compare to another variable (a very basic password protection). The function works great, however, if you click "cancel"
on the prompt()
window, the function does not simply terminate, but rather compares the variable to an empty string, (which the user opted not to submit by pressing "cancel" instead) resulting in the function continuing to the else{ }
portion.
My question is, how do I terminate the function upon pressing cancel? I just need to know how to target the cancel button.
Usually I would just call a .stop()
on the click()
of a button, but I don't know how to target the prompt-window's cancel button.
use event. target..it will give you target element reference. prompt returns null when the cancel button is pressed.
If the user clicks the Cancel button, prompt( ) returns null . If the user clicks the Clear button, prompt( ) erases any current text in the input field. If the user clicks the OK button, prompt( ) returns the value currently displayed in the input field.
A prompt box is used if you want the user to input a value. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed. Do not overuse this method. It prevents the user from accessing other parts of the page until the box is closed.
prompt
returns a string if the user presses OK
(''
being with no value submitted). If the user pressed Cancel
, null
is returned. All you need to do is check whether the value is null
:
function doSomething() { var input; input = prompt('Do something?'); if (input === null) { return; //break out of the function early } switch (input) { case 'fun': doFun(); break; case 'boring': beBoring(); break; } }
You should explicitly check for null
as the return value (using triple-equals) and return
when this is the result.
var result = prompt("OK?"); if (result === null) { return; }
This allows you to distinguish from the empty string, which is what's returned when the user clicks OK
but enters no content.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With