简体   繁体   中英

Unable to detect user pressing 'Cancel' from window.prompt()

According to what I've researched, the function should be able to detect whether input is empty or not as well as if 'Cancel' is pressed. However, only the first two things work and whenever I click on 'Cancel', nothing happens.

I've posted the whole function code, but my issue is with the if-else statement. I've tested this on IE7, Chrome and Firefox.

JavaScript:

function countStrings()
{
    var sequence = [];
    sequence = window.prompt( "Enter a sequence of values", "a 1 b 2" ).split( " " );
    if ( sequence[ 0 ] === "" )
    {
        // user pressed OK or Return; input is empty
    }
    else if ( sequence )
    {
        // user pressed OK or Return; input not empty.
    }
    else
    {
        // User pressed Cancel; not being detected/not working.
        // Nothing happens.
    }
}

HTML:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>Practice</title>
    <script type = "text/javaScript" src="./practice.js"></script>
</head>
<body id="beach_ready">
    <h1>Practising JavaScript functions</h1>
    <p>
        <input id="f" type="button" value="Function" onclick="countStrings();" />
        Click to the count number of strings in an array
    </p>
</body>
</html>
var sequence=window.prompt();

if (sequence===""){
//then I entered nothing and pressed OK
} else
if (sequence===null){
//then I pressed cancel.
} else {
//then I entered something good. process it
//..rest of your code...
}

To answer your question: null.split(" "); results in an error, because you can't call any methods on null , because its null and isn't an object and doesn't have methods to call.

So when this line happens

sequence = window.prompt( "Enter a sequence of values", "a 1 b 2" ).split( " " );

and the user presses cancel, this evaluates to sequence = null.split(" ") and your script bombs out. So you need to get the value first, see what it is, then don't call split on it until you have determined it's safe to do so. Like this:

var sequence, sequenceInput;
    sequenceInput = window.prompt( "Enter a sequence of values", "a 1 b 2" );
    if ( sequenceInput=== "" )
    {
        // user pressed OK or Return; input is empty
    }
    else if ( sequenceInput===null )
    {
        // user pressed cancel
    }
    else
    {
        //user entered something
        sequence=sequenceInput.split(" ");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM