Use JavaScript to format number with comma separator for thousands as you type

The other day a client asked me if it was possible to format a number using comma as a thousand separator as they typed into a text box. After doing a little bit of research and playing around, I came up with this solution.

Solution consist of two JavaScript functions – CheckNumeric() to check if the key pressed is a valid numeric value, and FormatCurrency() which formats the value in the text box. CheckNumeric() is bound to onkeypress and FormatCurrency() is bound to onkeyup events on the target textbox.


function FormatCurrency(ctrl) {
    //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
    if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40)
    {
        return;
    }

    var val = ctrl.value;

    val = val.replace(/,/g, "")
    ctrl.value = "";
    val += '';
    x = val.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';

    var rgx = /(\d+)(\d{3})/;

    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }

    ctrl.value = x1 + x2;
}

function CheckNumeric() {
    return event.keyCode >= 48 && event.keyCode <= 57;
}


onkeypress="return CheckNumeric();" onkeyup="FormatCurrency(this);"

Final result:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s