-2

I am performing calculator operation using javascript,in validating the input values everything is working fine except the divide by zero error, not able to figure out whats going wrong.. And its working fine with Chrome but not in Firefox!!

function validate(event, x, y, z) {
    if ((isNaN(x) || x === "") || (isNaN(y) || y === "")) {
        return "Please Enter A Valid Number";
    }
    if (z === "") {
        return "Invalid Operator";
    }
    if (z === '/' && y === 0) {
        return "Divide By zero error";
    }
    if (event.keyCode == 32) {
        return false;
    }
    if (event.keyCode == 8) {
        return false;
    } else {
        return calculation(x, y, z);
    }
}

DEMO

Tushar
  • 85,780
  • 21
  • 159
  • 179
  • Possible Dup of [Keycodes not working in Mozilla with Javascript](http://stackoverflow.com/questions/9834703/keycodes-not-working-in-mozilla-with-javascript) – Tushar Nov 25 '15 at 03:51
  • What are the values of *event*, *x*, *y* and *z*? How is the function called? Posted code should actually demonstrate the issue, so input values are important. – RobG Nov 25 '15 at 03:56
  • If I had to guess, *y* is a string so will never `=== 0` (otherwise `y === ""` will never be true). You should parse and validate all input first, then do the mathematics. – RobG Nov 25 '15 at 03:59
  • @Tushar—the OP doesn't seem to have a problem with that. It's the divide by zero test that fails (apparently in only one of two browsers but I can't see how that can be true). – RobG Nov 25 '15 at 04:04
  • I guess problem is with ===, if it is replaced with == will work fine. – Vishal Vijayan Nov 25 '15 at 04:11

2 Answers2

0

Based on your plunker you need to check the variable y for string '0'.

if (z === '/' && y === '0') {
    return "Divide By zero error";
}

This works in both the browsers.

Note: It failed in both the browsers too.

Charlie
  • 22,886
  • 11
  • 59
  • 90
0

The problem is with === operator as it also does strict checking(equal value and equal type). If you check the type of y using typeof() operator, you will find that it is a string. This will cause y===0 return false, if you change your code to y==="0" everything will work fine.

Vishal Vijayan
  • 308
  • 1
  • 4
  • 13