1

When the user types in the textbox i want it to format itself with decimals.

For example, if the user types 10000 I want it to show up like 10,000 while he types it.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Udantha
  • 77
  • 1
  • 4
  • 12

5 Answers5

1

Here you go. Handing backspace/delete made it especially challenging. That was fun! :-)

I have added this to my online portfolio of scripts at rack.pub.

function toast(a,b){b||(b=2750);var c={message:a,timeout:b};snackbarContainer.MaterialSnackbar.showSnackbar(c)}var doc=document,textArea=doc.getElementById("area"),numArray=[],backArray=[],num="",numF="",regx="",thisChar="",lastChar="",str="",index=0;window.snackbarContainer=doc.querySelector("#toast"),textArea.addEventListener("keydown",function(){var a=event.keyCode;if(str=this.value,(8==a||46==a)&&(backArray=[],index=str.length-1,lastChar=str.charAt(index),!isNaN(lastChar)||","==lastChar))for(var b=str.length-1;b>=0;b--){if(" "==str.charAt(b))return;if(isNaN(str.charAt(b))&&","!=str.charAt(b))return;backArray.push(str.charAt(b))}if(32==a&&backArray[1]){var c=backArray.reverse().slice(0,-1).join(""),d=c.replace(/\,/g,""),e=Number(d).toLocaleString().toString(),f=str.lastIndexOf(c);f>=0&&f+c.length>=str.length&&(str=str.substring(0,f)+e),this.value=str}}),textArea.addEventListener("keypress",function(){if(thisChar=this.value.slice(-1),isNaN(thisChar)){num=numArray.join(""),numArray=[],numF=Number(num).toLocaleString().toString(),regx=num+"(?!.*"+num+")",regx=new RegExp(regx);var a=this.value.replace(regx,numF);this.value=a}else{if(" "==thisChar){num=numArray.join(""),numArray=[],numF=Number(num).toLocaleString().toString(),regx=num+"(?!.*"+num+")",regx=new RegExp(regx);var a=this.value.replace(regx,numF);return void(this.value=a)}numArray.push(thisChar)}});
        html body {
            font-family: 'Roboto', sans-serif;
            background: #f5f5f5;
        }
        .text-right{
            text-align:right;
        }
        .text-center{
            text-align:center;
        }
        .text-left{
            text-align:left;
        }
        .thin{
            font-weight: 100;
        }
        .heading{
            font-size:3em;
        }
        .subtitle{
            margin-top: -16px;
        }
        #submit{
            margin-top:10px;
        }
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.2.0/material.indigo-pink.min.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,400" rel="stylesheet">

    <div class="demo-layout-transparent mdl-layout mdl-js-layout">
        <main class="mdl-layout__content page-content">
            
            <section class="mdl-grid">
                <div class="mdl-layout-spacer"></div>
                <div class="mdl-cell mdl-cell--4-col">
                    <h1 class="mdl-color-text--indigo-900 text-right thin">commas.js demo</h1>
                    <h6 class="mdl-color-text--indigo-500 text-right subtitle">
                        JavaScript to automatically add commas to numbers in a text area
                    </h6>
                </div>
                <div class="mdl-layout-spacer"></div>
            </section>
            
            <section class="mdl-grid">
                <div class="mdl-layout-spacer"></div>
                <div class="mdl-cell mdl-cell--4-col">
                    <h6 class="mdl-color-text--black thin">
                        Basically it auto formats numbers as you type in the text area.  Give it a try.
                    </h6>
                </div>
                <div class="mdl-layout-spacer"></div>
            </section>
            
            <section class="mdl-grid">
                <div class="mdl-layout-spacer"></div>
                <div class="mdl-textfield mdl-js-textfield mdl-cell mdl-cell--4-col">
                    <textarea class="mdl-textfield__input" type="text" rows= "3" id="area" ></textarea>
                    <label class="mdl-textfield__label" for="area">Type Here...</label>
                </div>
                <div class="mdl-layout-spacer"></div>
            </section>
            
        </main>
    </div>
        
    <!-- IE Compatibility shims DO NOT DELETE-->
      <!--[if lt IE 9]>
        <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js""></script>
      <![endif]-->

      <!--[if IE]>
        <script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/4.1.7/es5-shim.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/classlist/2014.01.31/classList.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/selectivizr/1.0.2/selectivizr-min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/flexie/1.0.3/flexie.min.js"></script>
        <link href="../assets/ie.css" rel="stylesheet">
      <![endif]-->
    <!-- end shims -->
    <script defer src="https://code.getmdl.io/1.2.0/material.min.js"></script>
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
0

use replace and a regex then just Queue that up on keyup.

$(selector).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//will replace with commas
0

That problem proved to be more challenging than I expected (I should have known better). Here is what I got, using vanilla Javascript.

You can set event handler for the onkeyup event of the TextBox:

<asp:TextBox ID="txtAutoFormat" runat="server" onkeyup="processKeyUp(this, event)" />

And here is the Javascript code:

<script type="text/javascript">

    function extractDigits(str) {
        return str.replace(/\D/g, '');
    };

    function findDigitPosition(str, index) {
        var pos = 0;
        for (var i = 0; i < str.length; i++) {
            if (/\d/.test(str[i])) {
                pos += 1;
                if (pos == index) {
                    return i + 1;
                }
            }
        }
    };

    function isCharacterKey(keyCode) {
        // Exclude arrow keys that move the caret
        return !(35 <= keyCode && keyCode <= 40);
    };

    function processKeyUp(txt, e) {
        if (isCharacterKey(e.keyCode)) {
            var value = txt.value;

            // Save the selected text range
            var start = txt.selectionStart;
            var end = txt.selectionEnd;
            var startDigit = extractDigits(value.substring(0, start)).length;
            var endDigit = extractDigits(value.substring(0, end)).length;

            // Insert the thousand separators
            txt.value = extractDigits(value).replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");

            // Restore the adjusted selected text range 
            txt.setSelectionRange(findDigitPosition(txt.value, startDigit), findDigitPosition(txt.value, endDigit));
        }
    };
</script>


Credits:

CMS's solution to extract digits from string in Regex using javascript to return just numbers.

Alan Moore's regular expression to insert thousand separators in How do I add thousand separators with reg ex?.

Note: Ron Royston's idea of using toLocaleString is also very interesting. It could provide a more universal solution. You could replace this line of processKeyUp:

txt.value = extractDigits(value).replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");

with the following:

txt.value = Number(extractNumber(value)).toLocaleString();
Community
  • 1
  • 1
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
-1

Try an input mask, here is an example: http://digitalbush.com/projects/masked-input-plugin/

Paritosh
  • 4,243
  • 7
  • 47
  • 80
-1

You can use jquery masking framework

references:

Jquery Masking

Source at git

Deepak
  • 1,510
  • 1
  • 14
  • 27