Can jQuery add commas while user typing numbers?

前端 未结 3 1693
猫巷女王i
猫巷女王i 2020-11-30 01:26

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 eventu

3条回答
  •  悲哀的现实
    2020-11-30 01:39

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

    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, ',');
    });

提交回复
热议问题