Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding commas to numbers when typing

I am trying to add commas when the user type a number. What is the correct syntax to select the input form-control class with attribute number type in Jquery?

EDIT: I can't change the HTML code since it is outputted from Django with Bootstrap.

HTML

<span class="input-group-addon">$</span>
<input class="form-control" id="id_step2-number_2"
       name="step2-number_2" type="number">
<span class="input-group-addon">.00</span>

JQuery

$(document).ready(function(){
    $("input[type='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("")
        );
          
        console.log(num2);

        // 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;
}

JSFiddle Link https://jsfiddle.net/yWTLk/767/

like image 661
jtd92 Avatar asked Dec 05 '14 08:12

jtd92


People also ask

How do you add commas to numbers?

First comma is placed three digits from the right of the number to form thousands, second comma is placed next two digits from the right of the number, to mark lakhs and third comma is placed after another next two digits from the right to mark crore, in Indian system of numeration.

How do you convert a number to a comma separated string?

Using toLocaleString() method The JavaScript toLocaleString() method is used to convert the elements of the given array into a string, and these Strings are separated by a comma ",".

How do you add a comma in a price in react JS?

To format a number with commas in React, we can use the number's toLocaleString method. We call toLocaleString on 1234.56789 with { maximumFractionDigits: 2 } to return a number string that has the comma digit separators and the rounded to 2 decimal places.


2 Answers

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.

like image 78
Hart Simha Avatar answered Sep 22 '22 12:09

Hart Simha


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"
like image 24
Leo Avatar answered Sep 18 '22 12:09

Leo