Cancel warning popup in javascript

Consider this code:

function reason(id) {
    var reason = prompt("State reason");
    while (!reason.trim()) {
        reason = prompt("Please enter text");
    }
    document.getElementById(id).value = reason;
    return true;
}

It works fine, but when I want to get rid of poppup by pressing escape, for example, the function returns true because the form is being executed. What to do to make it do nothing if I close / cancel poppup?

+4
source share
1 answer

... the function returns true because the form is executing. What to do to make it do nothing if I close / cancel poppup?

It all depends on how you call your function reason, but if you want it to reasonreturn falsewhen promptcanceled, then:

function reason(id) {
    var reason = prompt("State reason");
    while (reason !== null && !reason.trim()) {  // *** Changed
        reason = prompt("Please enter text");
    }
    if (reason === null) {                       // *** Added
        return false;                            // *** Added
    }                                            // *** Added
    document.getElementById(id).value = reason;
    return true;
}

promptreturns nullwhen canceled.

, , reason, - true false.


: , . , ...

+3

All Articles