Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
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())
})
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

var myInputs = document.getElementsByClassName('myInputs')

for(let i = 0; i < myInputs.length; i++){
  myInputs[i].addEventListener('change', function () {
   run_calculation(months_input.val(), salary_input.val(), monthly_raise_input.val())
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type = 'text' class='myInputs'>
<input type = 'text' class='myInputs'>
<input type = 'text' class='myInputs'>

about 4 years ago · Juan Pablo Isaza Report

0

You can use a class selector instead of an id and then use the "this" keyword with it to bind a function to the onchange

$(".class").on( "click", function() {
  run_calculation((this).val())
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!