ckaryuusai
ckaryuusai

Reputation: 67

Javascript comparing number giving wrong answer

I have a form in which the user fills in with a number, and then the value of that form is being compared to the measurement beside it. In this case, whenever I input the number 1, it looks like it's not being read, and it keeps giving me false results. It doesn't matter if it's 1, 10, 111, or 1111000 the output will always be false.

Here's the code snippet:

var elC4 = document.getElementById("elC4");
elC4.addEventListener("focusout", function () {
    var elE4 = document.getElementById("elE4");
    var val = elD4.value;
    var result = val.match(/\d/g);
    result = result.join("");
    console.log(elC4.value);
    console.log(result);
    console.log(elC4.value > result);

    if (elC4.value > result) {
        elE4.value = "Tidak Memenuhi";
    } else {
        elE4.value = "Memenuhi";
    }
});

console.log :

console.log output

The row I circled is the problematic one, the other ones have a similar function and work fine.

so what exactly is wrong?

Upvotes: 2

Views: 1673

Answers (2)

quachtinh761
quachtinh761

Reputation: 234

i think you're comparing 2 string. So, result is incorrect.

"10" > "2" ==> result is false

I suggest to compare like this:

+"10" > +"2" ==> result will be true ( in this case: +elC4.value > +result )

Hope this can help you, bro!

Upvotes: 3

meisam
meisam

Reputation: 485

seems like you are comparing two strings, while you actually have to compare two numbers.enter image description here

I would suggest to coerce those values to numbers, one way could be: adding a + behind those values: var elC4 = +document.getElementById("elC4");

Upvotes: 0

Related Questions