Search code examples
javascriptasp.net

Auto add comma (,) in text-box with numbers


My current coding adds comma (,) when there are 4 or more digits. But instead of 1101 = 1,101 my code is doing this 1101 = 110,1... I want it to format and bring the comma to the front. My javascript

<script language="javascript" type="text/javascript">   
    function AddComma(txt) {
        if (txt.value.length % 4 == 3) {
            txt.value += ",";
        }
    }
</script>


<asp:TextBox ID="TextBox3" onkeypress="AddComma(this)" runat="server"></asp:TextBox>

How do i format so the comma is in the front 1,101 or 10,101 or 100,101.


Solution

  • Try this code

    function Comma(Num) { //function to add commas to textboxes
            Num += '';
            Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
            Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
            x = Num.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;
        }
    
    
    <asp:TextBox ID="TextBox3" runat="server"  onkeyup = "javascript:this.value=Comma(this.value);" />
    

    Hope this helps you.