Javascript prompt() - cancel button to terminate the function

后端 未结 5 1106
自闭症患者
自闭症患者 2020-12-14 06:19

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). Th

相关标签:
5条回答
  • Try:

    message = prompt("Enter text");
    if(message == "null" || message == null || message == "" );
    

    This worked for me.

    0 讨论(0)
  • 2020-12-14 06:27

    Can you just check for

    if (prompt_responce == null)
    

    to tell if it is closed.

    0 讨论(0)
  • 2020-12-14 06:31

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-14 06:36

    One substantial problem with handling the result of 'prompt' is that Safari (at least version 9.1.2) returns "" instead of null when "Cancel" is clicked. This means that: if(result==null) return; does not work, and you cannot distinguish between entry of a null string, and cancellation.

    0 讨论(0)
  • 2020-12-14 06:45

    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.

    0 讨论(0)
提交回复
热议问题