Quantcast
Viewing all articles
Browse latest Browse all 32

Using jQuery to add thousands separator to textbox

UPDATED: Code improved after feedback from Henrik Tengelin.

It is much easier to read large numbers with with thousands separator but how to get them to work with page validation in a good way?

The solution in this case was to sprinkle some jQuery on the page!

Test how it works here

JavaScript code for adding thousands separator as watermark

$(function() {
    var numberInputs = $("input.number");
    var convertToCurrencyDisplayFormat = function(str) {
        var regex = /(-?[0-9]+)([0-9]{3})/;
        str += '';
        while (regex.test(str)) {
            str = str.replace(regex, '$1 $2');
        }
        str += ' kr';
        return str;
    };
    var stripNonNumeric = function(str) {
        str += '';
        str = str.replace(/[^0-9]/g, '');
        return str;
    };
    numberInputs.each(function() {
        this.value = convertToCurrencyDisplayFormat(this.value);
    });
    numberInputs.blur(function() {
        this.value = convertToCurrencyDisplayFormat(this.value);
    });
    numberInputs.focus(function() {
        this.value = stripNonNumeric(this.value);
    });
    $("form").submit(function() {
        numberInputs.each(function() {
            this.value = stripNonNumeric(this.value);
        });
    });
});


Viewing all articles
Browse latest Browse all 32

Trending Articles