0

document.querySelectorAll('#salary-min, #salary-max').addEventListener('input', event =>
  event.target.value = (parseInt(event.target.value.replace(/[^\d]+/gi, '')) || 0).toLocaleString('en-US')
);
<div id="salary-range">
  <div>
    <div class="input">
      <label for="salary">Minimum salary</label>
      <input class='inp_cont' id="salary-min" pattern="^[\d,]+$" name="salary" placeholder="Enter your salary" required="" type="text">
    </div>
  </div>
  <div>
    <div class="input">
      <label for="salary">Maximum salary</label>
      <input class='inp_cont' id="salary-max" pattern="^[\d,]+$" name="salary-max" placeholder="Enter your salary" required="" type="text">
    </div>
  </div>
</div>

I try to get both salary-min and salary-max to use the js code for comma separation. I tried also ElementsByClass and that also didnt work. How to have two IDs work in my js?

  • Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Sebastian Simon Oct 02 '17 at 00:11

1 Answers1

1

You can't call methods designed for a single element on a collection of elements.

Use a loop.

const handler = event => event.target.value = (parseInt(event.target.value.replace(/[^\d]+/gi, '')) || 0).toLocaleString('en-US');

for (const el of document.querySelectorAll('#salary-min, #salary-max')) {
  el.addEventListener('input', handler);
}

As a side note, your regex can be shortened from /[^\d]+/gi to /\D+/gi

llama
  • 2,535
  • 12
  • 11