使用javascript将asp.net网页上的文本框格式化为货币格式

时间:2014-02-20 13:21:29

标签: javascript asp.net currency formatting

我需要文本字段动态反应,也就是说如果用户按“1”,文本字段将显示为$ 0.01,然后2 = $ 0.12等等。

我花了最后5个小时试图找到这样做的java脚本无济于事。

my asp.net element= <asp:TextBox ID="txtAmountExclVat" runat="server" style="text-    align:right;" OnKeyUp="CurencyFormatting();"  OnTextChanged="txtAmountExclVat_TextChanged" ></asp:TextBox>

    <script language="javascript">
    function CurencyFormatting()
    {
        var display = document.getElementById("ContentPlaceHolder1_txtAmountExclVat").value;
        var number = display;
        if (number === null)
        { number = 0.0 }
        else
        {
            var length = number.length;
            if(length==1)
            {
                number = "R 0.0".concat(number);
            }
            if (length == 2)
            {
                number = "R 0.".concat(number);
            }
            if (length == 3)
            {
                var formatting = number.split("");
                number = "";
                number = "R ".concat(formatting[0]);
                number = number.concat(".");
                number=number.concat(formatting[1],formatting[2])
            } 
            if (length == 4)
            {
                var formatting = number.split("");
                number = "";
                number = "R".concat(formatting[0], formatting[1]);
                number = number.concat(".");
                number = number.concat(formatting[2], formatting[3]);
            }
            if (length == 5)
            { 
                var formatting = number.split("");
                number = "";
                number = "R ".concat(formatting[0], formatting[1],formatting[2]);
                number = number.concat(".");
                number = number.concat(formatting[3], formatting[4]);
            }
            if (length == 6)
            {
                var formatting = number.split("");
                number = "";
                number = "R ".concat(formatting[0], formatting[1], formatting[2], formatting[3]);
                number = number.concat(".");
                number = number.concat(formatting[4], formatting[5]);
            }
            display.value = number;


        }
    }

1 个答案:

答案 0 :(得分:0)

试试这个

<input type="text" id="myTextBox" onkeyup="formatNum(event)" />


<script type="text/javascript">
var abc=["0",".","0","0"];


function formatNum(e){

            var keynum;

            if(window.event){ // IE                 
                keynum = e.keyCode;
            }else
                if(e.which){ // Netscape/Firefox/Opera                  
                    keynum = e.which;
                 }

abc[0]=abc[2]
abc[1]=abc[1];
abc[2]=abc[3]
abc[3]=String.fromCharCode(keynum);
document.getElementById("myTextBox").value=abc.join('');

}
</script>