13

This does it incorrectly: Can jQuery add commas while user typing numbers?

  $('input.number').keypress(function(event){
      if(event.which >= 37 && event.which <= 40){
          event.preventDefault();
      }
      var $this = $(this);
      var num = $this.val().replace(/,/g, '');
      $this.val(num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
  });

I need "1000000" to be "1,000,000" or better with spaces "1 000 000".

Please help. Thanks.

Community
  • 1
  • 1
Alex G
  • 3,048
  • 10
  • 39
  • 78

5 Answers5

11

if you wanted to have something like "1 000 000", you can change the code to something like this.

  var num = $this.val().replace(/(\s)/g, '');
  $this.val(num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 "));

Hope this helps

XepterX
  • 1,017
  • 6
  • 16
  • Changing to space - not an issue. Script does not do proper positioning of commas. – Alex G Feb 06 '12 at 09:03
  • what do you mean by proper positioning of commas? do give an example – XepterX Feb 07 '12 at 02:06
  • XepterX - just run your code and type 1000000. You should see that it's NOT coming up with 1 000 000! – Alex G Feb 07 '12 at 09:33
  • just look at this fiddle, you might want to try it before you said my code won't work, http://jsfiddle.net/UMEZe/ – XepterX Feb 07 '12 at 10:28
  • 3
    You code on jsfiddle is not the same like you posted here. Lier!! =)) You've replaced keypress with keyup and things started to work! Thanks. – Alex G Feb 07 '12 at 10:50
  • @XepterX , I'm trying to play around with it, I only need a "," and no decimal, but when I replaced the '' on the "var num" line it would add a comma after every 0 and not after every 3 zeroes. Any chance you can point me to the right direction for that? Thanks! – gdubs Jul 31 '13 at 19:13
  • see the following question: http://stackoverflow.com/questions/2632359/can-jquery-add-commas-while-user-typing-numbers – sQuijeW Dec 06 '13 at 00:54
  • result of this input doesn't go for php database – AVI Feb 23 '17 at 05:41
  • i add function for change value format, so point auto place to end. i change value 4, so point auto move end. http://prntscr.com/eqjyzo – dungphanxuan Mar 31 '17 at 00:07
7
$(document).ready(function(){


    $('input.number').keyup(function(event){
      // skip for arrow keys
      if(event.which >= 37 && event.which <= 40){
          event.preventDefault();
      }
      var $this = $(this);
      var num = $this.val().replace(/,/gi, "").split("").reverse().join("");

      var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));

      // the following line has been simplified. Revision history contains original.
      $this.val(num2);});});

    function RemoveRougeChar(convertString){


    if(convertString.substring(0,1) == ","){

        return convertString.substring(1, convertString.length)            

    }
    return convertString;

}

Edit as you see fit - also in jsfiddle - jsFiddle

j0k
  • 22,600
  • 28
  • 79
  • 90
CR41G14
  • 5,464
  • 5
  • 43
  • 64
  • Thanks for the jsFiddle. This solution does work but has some bad usability when you try to enter digits at the front or middle of a number. Your cursor focus always ends up at the end of the number after each key-hit. – Luke May 15 '13 at 21:40
  • I see this also as the best answer here, but it has issues with standard user behaviors like typing in: $100000 - it treats the $ as an integer. I would upvote this were it not for that issue, and downvote all the other answers though because this one is almost perfect, with the caveat that it fails to handle non numerics properly. – Lizardx Nov 16 '15 at 22:30
6

You can use Digital Bush's Masked Input Plugin for Jquery. It has many options for customisation including spaces, eg:

$("#myInputText").mask("9 999 999",{placeholder:" "})

It seems to have been tested on different browser platforms so it could save you from some compatibility testing.

If you want a more comprehensive numeric mask support, you can use the excellent autoNumeric from decorplanit.com . Their webpage is full of examples.

Zero Distraction
  • 1,286
  • 3
  • 17
  • 24
  • I like it, but when I type 99 999 999 it does everything wrong. =) I guess I need to add commas every three digits but from right to left – Alex G Feb 06 '12 at 07:53
  • You can try `$("#myInputText").mask("99,999,999",{placeholder:" "}).css("textAlign","right")` to right align. The css `text-align` attribute just aligns the text to the right. – Zero Distraction Feb 07 '12 at 00:41
  • 1
    Come on. You gotta be kidding me? I don't need to align text to the right. =)))) Run your code and type 1000000 you will not get 1,000,000. – Alex G Feb 07 '12 at 09:38
  • Sorry mate, I mistook your problem with a fixed length mask (eg, phone numbers). I've used the plugin autoNumeric and it performed with reasonable success for numeric fields. I've edited the answer to add that. – Zero Distraction Feb 07 '12 at 23:21
0

I tried autoNumeric as @Zero-Distraction 's answer suggested, but I had some issues with cut/pasting into it. The CleaveJS library has a lot more popularity, a little more built-in functionality, and I didn't have the same issues with it. (demo website at https://nosir.github.io/cleave.js/ )

manroe
  • 1,645
  • 20
  • 35
-1

I tried to improve on j0k's code by instead using blur and focus events rather than keyup: http://jsfiddle.net/AqDda/

^ Try input A (standard type="number") versus input B (type="text" with JavaScript and some 'invalid' styling).

$('input.number').on("focus",function(e){
    var $this = $(this);
    var num = $this.val().replace(/,/g,"");
    $this.val(num);

}).on("blur", function(e){
    var $this = $(this);
    var num = $this.val().replace(/[^0-9]+/g, '').replace(/,/gi, "").split("").reverse().join("");     
    var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
    $this.val(num2);
});
Luke
  • 18,811
  • 16
  • 99
  • 115