Justin Ward Justin Ward - 2 years ago 270
Javascript Question

Javascript prompt() - cancel button to terminate the function

I'm calling a Javascript

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
on the
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{ }

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
on the
of a button, but I don't know how to target the prompt-window's cancel button.

Answer Source

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':
    case 'boring':
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download