Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I catch an `on change` event in JS once one of many elements change?

So I have several input fields that trigger a function once they change their value. Is there any way I can re-write and shorten this code? I keep repeating myself..

# .js

let months_input = $('#id_months')
let salary_input = $('#id_start_salary')
let monthly_raise_input = $('#id_monthly_raise')

months_input.on('change', function () {
  run_calculation(months_input.val(), salary_input.val(), monthly_raise_input.val())
})

salary_input.on('change', function () {
  run_calculation(months_input.val(), salary_input.val(), monthly_raise_input.val())
})

monthly_raise_input.on('change', function () {
  run_calculation(months_input.val(), salary_input.val(), monthly_raise_input.val())
})

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There’s multiple ways you can do what you’re trying to accomplish and reduce duplication.

You could wrap your inputs in some container element and allow event bubbling to handle this for you.

That might look like this

document.getElementById('foo').addEventListener('change', e => {
  console.log('input changed');
});
<div id="foo">
  <input id="one" />
  <input id="two" />
  <input id="three" />
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading