Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript prompt() - cancel button to terminate the function

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.

like image 336
Justin Ward Avatar asked Oct 12 '12 17:10

Justin Ward


People also ask

How do I stop a Javascript prompt?

use event. target..it will give you target element reference. prompt returns null when the cancel button is pressed.

What does clicking on Cancel button in the prompt dialog box?

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.

What is prompt box in HTML?

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.


2 Answers

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;     } } 
like image 120
zzzzBov Avatar answered Sep 22 '22 05:09

zzzzBov


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.

like image 43
Wayne Avatar answered Sep 21 '22 05:09

Wayne