我想在输入框输入钱的时候,他会自动加上,号,比如我输入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>
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);
}
};
});