How would I go about dynamically adding commas as a user is entering numbers? Is there a good number formatter that would help? I have to add these numbers later so I eventually have to remove the commas down the line. But the screen needs to show the commas for better readability.
当用户输入数字时,我将如何动态添加逗号?是否有一个很好的数字格式化器有帮助?我必须稍后添加这些数字,所以我最终必须删除逗号。但屏幕需要显示逗号以提高可读性。
2 个解决方案
#1
67
Run the code snippet to see it work
运行代码段以查看它是否有效
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">
#2
1
Here's an implementation of @maček's answer in vanilla JS if you don't want to use jQuery:
如果您不想使用jQuery,这里是@maček在vanilla JS中的答案的实现:
var el = document.querySelector('input.number');
el.addEventListener('keyup', function (event) {
if (event.which >= 37 && event.which <= 40) return;
this.value = this.value.replace(/\D/g, '')
.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
});
<input class="number">
#1
67
Run the code snippet to see it work
运行代码段以查看它是否有效
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">
#2
1
Here's an implementation of @maček's answer in vanilla JS if you don't want to use jQuery:
如果您不想使用jQuery,这里是@maček在vanilla JS中的答案的实现:
var el = document.querySelector('input.number');
el.addEventListener('keyup', function (event) {
if (event.which >= 37 && event.which <= 40) return;
this.value = this.value.replace(/\D/g, '')
.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
});
<input class="number">