Javascript: comparing two values always not equal

if statementjavascript

I'm trying to do something but im struggling with a stupid bug, hope you can help me.

As you can see in my code I have on server some check box and I attached to it a JavaScript function. This function gets two values (current value and original value).
My problem is when this function triggers on the if it always get to the first clause and never reach the else clause and it doesn't make any sense.

When I used few alerts in my code this is what happens:

case 1: alert #1 original: false current: true alert #2 true

case 2: alert #1 original: false current: false alert #2 true

As you can see, no matter what I get true on the 2nd alert.

Hope I managed to explain my problem.

<asp:CheckBox id="chkIsCustomQuantity" originalvalue="false" runat="server" onclick="checkChange(this.checked, this.attributes['originalvalue'].value" />

<script type="text/javascript" language="javascript">
    function checkChange(value, originalValue) {

        //i added this for debugging purpose
        alert('original: ' + originalValue + ' ' + 'current: ' + value);
        alert(value != originalValue);

        if (value != originalValue) {
             // always happens
        }
        else {
              // never happens
        }
    }

</script>

Best Answer

originalValue is always a string. value is a boolean. So, they're never equal, but when you print them out they appear identical (since they're both converted to the same string value at that point).

You can fix this in a variety of ways. One simple way is to convert both to strings first:

if (String(value) != String(originalValue))