Matt
Matt

Reputation: 5660

Can jQuery add commas while user typing numbers?

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.

Upvotes: 39

Views: 64464

Answers (3)

Jhomar
Jhomar

Reputation: 1

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

Upvotes: 0

aboutaaron
aboutaaron

Reputation: 5389

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, ',');
});
<input class="number">

Upvotes: 6

maček
maček

Reputation: 77778

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

Upvotes: 109

Related Questions