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>
阅读 5k
2 个回答

用 on('propertychange input') 试试

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);
        }
    };
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题