JavaScript Prompt Box Cancel Button?

自作多情 提交于 2019-11-30 19:53:48

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.

user3734688

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.

Yeah, my suggested comment does work

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

JSFiddle

Hackerman
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!");
}
var message = prompt('type any...', '');
if(message+'.' == 'null.')
{
    alert("you've canceled");
}
else
{
    alert("type ok");
}
                $.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!!!');
                        }
                    }
                });     
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!