0

I'm developing a calculator in Javascript.

I have multiple inputs with the same class that share a common behavior when "oninput" is triggered:

let sliders = document.getElementsByClassName('slider');
for(let i = 0; i < sliders.length; i++) {
    sliders.item(i).oninput = function() {
        let txtValue = this.getAttribute('id') + 'Text'; //The Input field that will display the numeric value of the slider

        element(txtValue).value = (element(txtValue).getAttribute('format') == 'currency') ?
        formatNumber(this.value, 0) : this.value;
    };
} 

The sliders "oninput" event updates the text-boxes below them with the user friendly values

BUT, my problem is, outside that I need a separate oninput listener for the Down Payment slider, because I also want to update the percentage shown to the right, so, when I try to add a new line of code like this:

element('downPayment').oninput = function() {
    element('downPaymentPercentageText').value = (element('downPayment').value / element('loanAmount').value) * 100;
}

It just doesn´t work, any idea how can I listen twice to the "oninput" to trigger two trigger these two different handlers?

2
  • you can just have another function and call it inside the event listener, you can even have it called/run based on condition. Commented Apr 12, 2020 at 13:38
  • 1
    Thank you! The answer below solves it all the proper way. Commented Apr 12, 2020 at 13:42

1 Answer 1

3

Replace your oninput = handler with addEventListener('input', handler). Read more about addEventListener on MDN, but you can attach as many handlers as you'd like.

element('downPayment').addEventListener('input', function() {
    element('downPaymentPercentageText').value = (element('downPayment').value / element('loanAmount').value) * 100;
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! How could I not think about it!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.