0

I have this code to compare two values to verify they are identical:

$(document).on("blur", "[id$=boxSection5Total]", function (e) {
    var totalvalue = $(this).val();
    var paymenttotalvalue = $('[id$=boxPaymentAmount]').val();
    if (totalvalue != paymenttotalvalue) {
        console.log("The value in 'Total' does not equal the previous value in 'Payment Total.'");
        alert("The value in 'Total' does NOT equal the previous value in 'Payment Total.' payment total is " + paymenttotalvalue + " and total is " + totalvalue);
    }
    else {
        console.log("The value in 'Total' DOES equal the previous value in 'Payment Total'");
    }
});

However, if both text elements are left blank, it fails - they are considered to not be equal (the "if (totalvalue != paymenttotalvalue)" condition is true).

How can I refactor the code so that it ignores cases where both elements have been left blank?

Something like:

$(document).on("blur", "[id$=boxSection5Total]", function (e) {
    var totalvalue = $(this).val();
    var paymenttotalvalue = $('[id$=boxPaymentAmount]').val();
    if ((totalvalue == null) & (paymenttotalvalue == null)) {
        return;
    }
    . . .
});

?

Both "boxSection5Total" and "boxPaymentAmount" are text elements (textboxes).

Anders
  • 8,307
  • 9
  • 56
  • 88
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    The value will not be 'null' and `"" == null` is false. The simplest - and most idiomatic - change to the existing would be `if (!totalvalue && !paymenttotalvalue) { return; }`, but likely better to combine with the other conditional. – user2864740 Jul 07 '15 at 22:09
  • 1
    @up true, if it comes from html form its mostly considered as empty value – itwasntme Jul 07 '15 at 22:11

2 Answers2

2

If these are in fact blank text values then use....

if(totalvalue === "" && paymenttotalvalue === "")
{
    return;
}

or (i think)

if(totalvalue == 1 && paymenttotalvalue == 1)
{
    return;
}
CommonKnowledge
  • 769
  • 1
  • 10
  • 35
2

If you want to check specifically on null you should try something like this.

if (totalvalue !== null && paymenttotalvalue !== null && totalvalue != paymenttotalvalue)

If you want to check for untruthy (also see here: JavaScript: how to test if a variable is not NULL) you can use this:

if (totalvalue && paymenttotalvalue && totalvalue != paymenttotalvalue)
Community
  • 1
  • 1
mwoelk
  • 1,182
  • 10
  • 14