search

Home  >  Q&A  >  body text

javascript - input文本框自动加钱格式

我想在输入框输入钱的时候,他会自动加上,号,比如我输入123456789
他会自动处理成12,345,678,9
而不是输入完后在变成12,345,678,9
有什么事件可以做到的,用onkeyup和onkeydown没用

<!doctype html>
<html>
    <head><meta charset="utf-8" /><title>无标题文档</title>
    </head>
    <body>
        <input type="text" id="textbox"/>
    </body>
        <script>
                function formatCurrency(num) {
                num = num.toString().replace(/\$|\,/g, '');
                if (isNaN(num))
                    num = "0";
                sign = (num == ( num = Math.abs(num)));
                num = Math.floor(num * 100 + 0.50000000001);
                cents = num % 100;
                num = Math.floor(num / 100).toString();
                if (cents < 10)
                    cents = "0" + cents;
                for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
                    num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
                return (((sign) ? '' : '-') + num + '.' + cents);
            }
            var s=document.getElementById("textbox");
            s.onchange=function(){
                this.value=formatCurrency(this.value);
            }
        </script>
</html>
巴扎黑巴扎黑2914 days ago293

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-10 15:25:36

    用 on('propertychange input') 试试

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 15:25:36

    jquery

    https://github.com/flaviosilveira/Jquery-Price-Format


    angularjs

    app.directive('price', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, element, attr, ngModel) {
                function parse(string) {
                    var v = parseFloat(string) || 0;
                    return parseInt(v * 100);
                }
    
                function format(string) {
                    var v = parseInt(string) || 0;
                    return parseFloat(v / 100).toFixed(2);
                }
                ngModel.$parsers.push(parse);
                ngModel.$formatters.push(format);
            }
        };
    });
    

    reply
    0
  • Cancelreply