dames
dames

Reputation: 1481

How do I add Thousands separator to my html form

For example i have a textbox, I am entering 12000 and i want it to look like 12,000 in the textbox How would I do this? Im using html to do the textbox

Upvotes: 12

Views: 68216

Answers (8)

Bud Damyanov
Bud Damyanov

Reputation: 31829

You can use very handy JavaScript method, called Intl.NumberFormat:

<script>
//Value formatting  
document.getElementById('your-input-id').addEventListener('change', function(event) {
    //Check for specific CSS class of your input first
    if (event.target.classList.contains('some-css-class')) {
        // remove any commas from earlier formatting
        const value = event.target.value.replace(/,/g, '');
        // try to convert to an integer
        const parsed = parseInt(value);
        //NumberFormat options
        const options = {
            style: 'decimal',
            maximumFractionDigits: 10,
            useGrouping: true,
            maximumSignificantDigits: 20,
        };
        // check if the integer conversion worked and matches the expected value
        if (!isNaN(parsed) && parsed == value) {
            // update the value
            event.target.value = new Intl.NumberFormat('en-GB', options).format(value);
        }
    }
  });
  </script>

Upvotes: 0

Muhammad Muzamil
Muhammad Muzamil

Reputation: 1242

adding punctuation or commas of numbers on input change.

html code

 <input type="text"  onkeyup="this.value=addPunctuationToNumbers(this.value)">

Javascript Code

<script>
    function addPunctuationToNumbers(number) {
        return number.replace(/(\d{3})(?=\d)/g, "$1,");
    }
</script>

   

 <!DOCTYPE html>
    <html>
    <body>

    <h1>On change add pumctuation to numbers</h1>

    <input type="text"  onkeyup="this.value=addPunctuationToNumbers(this.value)">


    <script>
        function addPunctuationToNumbers(number) {
            return number.replace(/(\d{3})(?=\d)/g, "$1,");
        }
    </script>
    </body>
    </html>

Upvotes: 0

Asuquo12
Asuquo12

Reputation: 835

You can try this simple Javascript

<script type="text/javascript">

    function addcommas(x) {
    //remove commas
    retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;

    //apply formatting
    return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
  </script>

HTML Code

<div class="form-group">
                        <label>Amount </label>
                        <input type="text" name="amount"  onkeyup="this.value=addcommas(this.value);"class="form-control" required="">
                      </div>

Upvotes: 3

Csq
Csq

Reputation: 5855

Use the jQuery autoNumeric plugin:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Input with separator</title>
  <script type="text/javascript" src="jquery-1.11.0.js"></script>
  <script type="text/javascript" src="autoNumeric.js"></script>
  <script type="text/javascript">
    $( document ).ready( function() {
      $("#myinput").autoNumeric(
        'init', {aSep: ',', mDec: '0', vMax: '99999999999999999999999999'}
      );
    });
  </script>
</head>
<body>
  <input id="myinput" name="myinput" type="text" />
</body>
</html>

Upvotes: 8

kennebec
kennebec

Reputation: 104760

This is probably a bad idea...

<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Comma Thousands Input</title>
<style>
label, input, button{font-size:1.25em}
</style>
<script>
// insert commas as thousands separators 
function addCommas(n){
    var rx=  /(\d+)(\d{3})/;
    return String(n).replace(/^\d+/, function(w){
        while(rx.test(w)){
            w= w.replace(rx, '$1,$2');
        }
        return w;
    });
}
// return integers and decimal numbers from input
// optionally truncates decimals- does not 'round' input
function validDigits(n, dec){
    n= n.replace(/[^\d\.]+/g, '');
    var ax1= n.indexOf('.'), ax2= -1;
    if(ax1!= -1){
        ++ax1;
        ax2= n.indexOf('.', ax1);
        if(ax2> ax1) n= n.substring(0, ax2);
        if(typeof dec=== 'number') n= n.substring(0, ax1+dec);
    }
    return n;
}
window.onload= function(){
    var n1= document.getElementById('number1'),
    n2= document.getElementById('number2');
    n1.value=n2.value='';

    n1.onkeyup= n1.onchange=n2.onkeyup=n2.onchange= function(e){
        e=e|| window.event; 
        var who=e.target || e.srcElement,temp;
        if(who.id==='number2')  temp= validDigits(who.value,2); 
        else temp= validDigits(who.value);
        who.value= addCommas(temp);
    }   
    n1.onblur= n2.onblur= function(){
        var temp=parseFloat(validDigits(n1.value)),
        temp2=parseFloat(validDigits(n2.value));
        if(temp)n1.value=addCommas(temp);
        if(temp2)n2.value=addCommas(temp2.toFixed(2));
    }
}
</script>
</head>
<body>
<h1>Input Thousands Commas</h1>
<div>
<p>
<label> Any number <input id="number1" value=""></label>
<label>2 decimal places <input id="number2" value=""></label>
</p></div>
</body>
</html>

Upvotes: 4

Mark Walters
Mark Walters

Reputation: 12390

Try something like this

function addCommas(nStr)
{
    nStr += '';
    x = nStr.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');
    }
    return x1 + x2;
}

Then use it on your textboxes like so

<input type="text" id="txtBox" onchange="return addCommas(this.value)" />

Hope that helps

Upvotes: 14

Curtis
Curtis

Reputation: 103348

For user input I would recommend not formatting the value to include a comma. It will be much easier to deal with an integer value (12000), than a string value (12,000) once submitted.

However if you are certain on formatting the value, then as @achusonline has recommended, I would mask the value. Here is a jQuery plugin which would be useful to get this result:

http://digitalbush.com/projects/masked-input-plugin/

Upvotes: 2

redDevil
redDevil

Reputation: 1919

You can use the Javascript Mask API

Upvotes: 3

Related Questions