javascriptjquerynullonblurhtmltext

How can I ignore two null or unassigned values in jQuery?


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).


Solution

  • 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)