[Fixed]-Adding commas to numbers when typing

19đź‘Ť

First of all, you can’t use input type=number, because it won’t allow the character , which you are using to notate number group.

Second, with a good regular expression, this is actually super easy, and really no need for reverse and reverse, which is boring.

var num = $this.val().replace(/,/gi, "");
var num2 = num.split(/(?=(?:\d{3})+$)/).join(",");

The first line removes commas from input value.
The second line is magic, it splits the value into groups of 3 from last to first, then join with comma. For example, '1234567' will become ['1', '234', '567'].

I use split here is just to show the power of RegExp, in practice we don’t need to split and join, just replace directly:

var num2 = num.replace(/\d(?=(?:\d{3})+$)/g, '$&,');

fiddle

But, the real magic is, I bet you would yell, toLocaleString! What?!

(1234567).toLocaleString() // "1,234,567"
👤Leo

8đź‘Ť

Using the input type “number” seems to prevent inserting commas into the input field with Javascript. If you’d like to insert commas, you may want to use a “text” input instead, but this will prevent numeric validation on browsers with Javascript disabled.

The fun will never end, it’s HTML5.

👤Hart Simha

5đź‘Ť

Change type="number" to type="text" because you can’t put comma into number.

<input class="form-control" id="id_step2-number_2"
       name="step2-number_2" type="text">

Check updated Fiddle

👤Bhumi Shah

0đź‘Ť

As many people are not using jQuery nowadays, here is a simple example with vanilla javascript.
You might have different use cases to add comma-separated values for numbers. Here is a complete guide to using commas as thousand separated using javascript.

let inputElement = document.querySelector("#number_element");
         inputElement.addEventListener("keyup",(event)=>{
      var tempNumber = inputElement.value.replace(/,/gi, "");
      var commaSeparatedNumber = tempNumber.split(/(?=(?:\d{3})+$)/).join(",");
      inputElement.value = commaSeparatedNumber;
     })
<input id="number_element" type="text">
<span>.00</span>
👤Sanan Ali

Leave a comment