SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2008
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question add commas to a number on change

    this is a simple test page with a text field that will take an integer (e.g. 1000) and change it to a string (e.g. 1,000) once you click off. it works great when you append the number (example: if you have 1,000 and add another 0 onto it, it will change it to be 10,000) until it gets to 1,000,000. problem is, if you add another 0 onto 1,000,000 it will write it as 1,000,0,000 rather than 10,000,000. i appreciate any help, thanks!

    HTML Code:
    <html>
    <head>
    <title>comma test</title>
    <script type="text/javascript">
    function addCommas()
    {
    	//wrote this first part to remove commas and then reevaluate where they should go
    	num = document.getElementById('value').value.replace(/,/, ''); 
    	x = num.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');
    	}
    	document.getElementById('value').value = x1 + x2;
    }
    </script>
    </head>
    <body>
    <input type="text" id="value" name="value" onchange="addCommas()" />
    </body>
    </html>

  2. #2
    Function Curry'er JimmyP's Avatar
    Join Date
    Aug 2007
    Location
    Brighton, UK
    Posts
    2,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You need to do perform a global match within "replace()" -

    Code JavaScript:
    replace(/,/g, '')
    James Padolsey
    末末末末末末末末末末末末末末末末末末末
    Awesome JavaScript Zoomer (demo here)
    'Ajaxy' - Ajax integration solution (demo here)

  3. #3
    SitePoint Enthusiast
    Join Date
    Jan 2008
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Talking

    ah, there's the problem! thanks! works perfect now )


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •