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); }); }); });



Henrik Tengelin gave me some valuable feedback so I have updated the script above.
It does not pollute the global namespace with its two conversion functions. Instead they are declared locally instead.
I do reuse the lookup of input elements to increase performance and also use this.value direct instead of the jQuery wrapper that does the same.
Also sprinkled some semicolons to make jslint happy and this also improves performance a little.
Hello dear, I used this technique but if i need to insert comma inplace of white space separator than how can i do ???
Try change this line and replace the space with a comma:
str = str.replace(regex, ‘$1 $2′);
Looks great. But why not create a jQuery plugin instead?
$(‘#myTextbox’).TheNameOfThePlugin();
Yes, that could be a good idea. And you could have options for currency and similar things. I put it on my to do list for research since I have never written a jQuery plugin before!
I wrote an article about that for a while ago:
http://weblogs.asp.net/mikaelsoderstrom/archive/2008/11/06/bygg-ut-jquery.aspx
Good luck!