Search code examples
javascriptjqueryinputnumberformatter

Ignoring null input with NumberFormatter in jquery


I have a series of input boxes that being formatted with the popular Number Formatter plugin for jQuery. It's fantastic, except that if you tab through an empty input box, it formats it with the trailing decimals being 0. So for currency with cents, it'd return '.00'.

The code I was going to use to solve the problem was simply something like so:

if ($(this) != "")
{
    $(this).parseNumber({ format: "#,###.00", locale: "us" });
    $(this).formatNumber({ format: "#,###.00", locale: "us" });
}

I've also tried 'null' instead of a blank set, but to no avail. I'm not super great at JS, so I'm guessing something silly is missing, as oft the case.

How can I get the NumberFormatter plugin to ignore empty input boxes?


Solution

  • $(this) is an object. You want to use $(this).val() to make sure the field has been filled out. This should work:

    if($(this).val()) { // Will evaluate to false if undefined or null
        $(this).parseNumber({ format: "#,###.00", locale: "us" });
        $(this).formatNumber({ format: "#,###.00", locale: "us" });
    }