javascript - Adding space between numbers? -


i'm trying make number input. i've made textbox accepts numbers via code:

function isnumber(evt) {     evt = (evt) ? evt : window.event;     var charcode = (evt.which) ? evt.which : evt.keycode;     if (charcode > 31 && (charcode < 48 || charcode > 57)) {         return false;     }     return true; } 

but question comes to, how create spaces user typing in number, iphone's telephone spacing thing, numbers example if type in: 1000 become 1 000;

1 10 100 1 000 10 000 100 000 1 000 000 10 000 000 100 000 000 1 000 000 000 

etc...

i've tried read input right each 3 characters , add space. way inefficient , when i'm changing value 1000 1 000 in textbox, selects reason, making key press after that, erase whole thing.

if know how this, please refrain using javascript plugins jquery. thank you.

for integers use

function numberwithspaces(x) {     return x.tostring().replace(/\b(?=(\d{3})+(?!\d))/g, " "); } 

for floating point numbers can use

function numberwithspaces(x) {     var parts = x.tostring().split(".");     parts[0] = parts[0].replace(/\b(?=(\d{3})+(?!\d))/g, " ");     return parts.join("."); } 

this simple regex work. https://developer.mozilla.org/en-us/docs/javascript/guide/regular_expressions << find more regex here.

if not sure whether number integer or float, use 2nd one...


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -