raulbaros raulbaros - 3 years ago 205
Javascript Question

querySelectorAll for numeric boxes do not work



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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download