1

I'm trying to dynamically insert commas into each text input as you type numbers. However, it's only working for the first input and I can't figure out why.

Here's my code:

HTML

<input type="text" class="number" id="annual-income" name="annual_income">
<input type="text" class="number" id="commission" name="commission">
<input type="text" class="number" id="bonus" name="bonus">
<input id="income-button" type="button" value="Next">

Javascript

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, ',');
  });
Anne
  • 13
  • 2

2 Answers2

0

Because you've only hooked it up to the first element. To select all of them, you need querySelectorAll. Then you need to loop through them. Along these lines:

// The function we'll use for handling keyup
function handleKeyUp(event) {
    if (event.which >= 37 && event.which <= 40) return;

    this.value = this.value.replace(/\D/g, '')
      .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// Get the list of inputs
var list = document.querySelectorAll('input.number');

// Add the event listener to them:
Array.prototype.forEach.call(list, function(el) {
    el.addEventListener('keyup', handleKeyUp);
});

That forEach trick is just one of several ways you could do the loop through the array-like collection from querySelectorAll. See the various "For Array-Like Objects" options in this answer (also mine).

You might also look into using event delegation rather than hooking the event on each input (since keyup does bubble).

Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
0

Select All elements using querySelectorAll, then iterate over them and add event listener for all of them. Check below snippet!

var allEls = document.querySelectorAll('input.number');

 for (var i=0; i<allEls.length; i++){
      var el = allEls[i];
      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 type="text" class="number" id="annual-income" name="annual_income">
<input type="text" class="number" id="commission" name="commission">
<input type="text" class="number" id="bonus" name="bonus">
<input id="income-button" type="button" value="Next">
Polynomial Proton
  • 4,421
  • 15
  • 37