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, '$&,');
But, the real magic is, I bet you would yell, toLocaleString
! What?!
(1234567).toLocaleString() // "1,234,567"
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.
- Related name for recursive many to many relationship not working
- Django 1.6 where is the User field 'last_login' updated?
- Why __unicode__ doesn't work but __str__ does?
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
- Django/Celery multiple queues on localhost – routing not working
- How to use the user_passes_test decorator in class based views?
- Django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)")
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>
- AssertionError: The field ' ' was declared on serializer ' ', but has not been included in the 'fields' option
- Remove autofocus attribute from field in Django
- Django reset_password_confirm TemplateSyntaxError problem
- 'instancemethod' object has no attribute '__getitem__'