Javascript prompt() - cancel button to terminate the function

Justin Ward picture Justin Ward · Oct 12, 2012 · Viewed 79.2k times · Source

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.

Answer

zzzzBov picture zzzzBov · Oct 12, 2012

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;
    }
}