jQuery 可以在用户输入数字时添加逗号吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2632359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:54:52  来源:igfitidea点击:

Can jQuery add commas while user typing numbers?

jqueryjquery-plugins

提问by Matt

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.

当用户输入数字时,我将如何动态添加逗号?有没有好的数字格式化程序可以帮助?我必须稍后添加这些数字,因此我最终必须删除行中的逗号。但是屏幕需要显示逗号以获得​​更好的可读性。

回答by ma?ek

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">

回答by aboutaaron

Here's an implementation of @ma?ek's answer in vanilla JS if you don't want to use jQuery:

如果您不想使用 jQuery,这里是 @ma?ek's answer 在 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">

回答by Jhomar

        <script>
        function costt() {   
        var costs = document.getElementById('cost').value;   
            if(costs != '') {          
     //   alert("ok");     
                cost.value = cost.value.replace(/\D/g, '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            } else {             
     //   alert("lol");     
                cost.value= 0;
            }        
        }
        </script>