开发者

Javascript Prompt Cancelled Not Behaving in While Loop

I have a prompt that basically is a required field and cannot contain a decimal. I have a while loop that should continue to prompt the user for information until a number is indicated regardless of whether OK or Cancel are clicked. Everything works fine as long as the OK button is clicked. It continues to prompt if left blank and OK is clicked or if a number with a decimal is provided and OK is clicked. But if cancel is clicked, it doesn't continue to 开发者_StackOverflowprompt.

var rmiles = prompt("Please indicate actual miles driven for payroll");
    while (rmiles == null | rmiles == "null" | rmiles == " " | rmiles.indexOf(".") != -1) {
        alert("Mileage is required when arriving on site and can only be whole numbers.  No Decimals.  Please enter 0 if you did not intend to arrive on site.");
        rmiles = prompt("Please indicate actual miles driven for payroll");
    }


I believe the problem is in your while condition - you are doing bitwise OR | on all the conditions. This means that rmiles.indexOf(".") is always called, even when rmiles is set to null by prompt when Cancel is clicked. This is because bitwise OR will not short-circuit.

Try the logical OR || which does short-circuit and thus avoids the null reference error:

while (rmiles == null || /*...*/


Because rmiles is null when the user clicks 'cancel'... so rmiles.indexOf produces an error/exception and kills the loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜