简体   繁体   中英

JavaScript: Functions - How to activate cancel button

I'm calling a Javascript window.prompt() and prompting the user to submit an integer number one at a time. if user click "cancel" on the prompt() window, the function should terminate the session but I could not find the function to solve this problem.

My question is, how do I terminate the function upon pressing cancel?

This is my program:

function isOdd(n) 
{
    return n % 2 == 1; // Checking if the number is odd or not
}


    // sentinel-controlled loop here
    while (true) {
        var n = Number(prompt("Enter an integer (click Cancel to terminate)", "0"));

        if(n === -1) {
            break;
            }
    if(isOdd(n)) {
        alert(n + " is odd.");
        }   
    else {
        alert(n + " is even.");
        }
    }

    // trying to find a solution for cancel button
    //document.getElementById("Button ID").click()

    //function cancel () {
        //var cancelButton = document.getElementById( "cancel");
        //}


    </script>
</head>

<body>
    <form action = "#">
        <input id = "cancel" type = "button" value = "cancel">
    </form>

    <h1>Odd/Even Output</h1>

</body>

"If the user clicks the Cancel button, this function returns null."

var promptResult = prompt(...)

if(!promptResult) {
   break;
}
// parse and rest of the function

Window.prompt returns null if the cancel button is clicked. You need to add in a case to handle that.

var result = prompt("Enter an integer (click Cancel to terminate)", "0");
if(result === null) {
    return;
}
var n = Number(result);

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