JavaScript Prompt Box Cancel Button?

后端 未结 6 998
情歌与酒
情歌与酒 2021-01-05 07:27

I have a JavaScript function as follows:

function popup(username) {
var req = createAjaxObject();
var message = prompt(\"Message:\",\"\");
if(message != \"\"         


        
相关标签:
6条回答
  • 2021-01-05 07:36
    var message = prompt('type any...', '');
    if(message+'.' == 'null.')
    {
        alert("you've canceled");
    }
    else
    {
        alert("type ok");
    }
    
    0 讨论(0)
  • 2021-01-05 07:38

    In the case of Cancel, the prompt result is null, and null != '' (as per ECMA-262 Section 11.9.3).

    So, add an extra explicit check for null inequality:

    if(message != "" && message !== null) {
    

    However, since the message is either some string or null and you only want to pass when it's a string with length > 0, you can also do:

    if(message) {
    

    This means: if message is truthy (i.e. not null or an empty string, amongst other falsy values), then enter the if clause.

    0 讨论(0)
  • 2021-01-05 07:45

    Are you using Safari by any chance? I have found that Safari seems to be returning empty string instead of null when the user clicks Cancel.

    See here: Safari 5.1 prompt() function and cancel.

    0 讨论(0)
  • 2021-01-05 07:51

    Yeah, my suggested comment does work

    var message = prompt("Message:","");
    if(message){
        alert("Not working!");
    } else {
        alert("Working!");
    }
    

    JSFiddle

    0 讨论(0)
  • 2021-01-05 07:53
                    $.messager.prompt('Save To File', 'FileName:', function(e){
                        if (e.response!='undefined'){
                            if (r!="")
                            {   
                              alert('Your FileName is:' + r);   
                            }
                            else
                            {
                              $.messager.alert('Err...','FileName cannot empty!!!');
                            }
                        }
                    });     
    
    0 讨论(0)
  • 2021-01-05 07:57
    var message = prompt("Message:","");
    if(message){
        alert("Message accepted, now i can process my php or script and blablabla!");
    } else {
        alert("Cancel Press or Empty Message, do nothing!");
    }
    
    0 讨论(0)
提交回复
热议问题