JavaScript: How to calc a formula instantly base on value put into the input fields?

Hi there, is anyone good at js can give a hint on how to do this?

<input id="a">
<input id="b">
<p id="result">0</p>

Calculate with a formula base on input values in a and b fields.
And write the result on the <p> with id="result", replacing the initial 0.
The result should be calculated and show up instantly when inputting the value.

Actually, the real case is like this: https://codepen.io/pen/vYRzVXG
Obviously, I’ve got something wrong and it does not work.

window.onload = function () {
  calcFee();
};

function calcFee() {
  var valueA = document.getElementById("input-01").value;
  var valueB = document.getElementById("input-02").value;
  const capicity = valueA * 288;
  document.getElementById("calc-bottles").textContent = capicity;
  document.getElementById("calc-price").innerHTML =
    capicity * 3.2 * 12 * valueB;
}

So much appreciated if anyone can help :raised_hands:
Thanks.

HI @anthonychan2509 did you tried onkeyup?

const [...inputs] = document.querySelectorAll(".w-input")
inputs.forEach(input =>
        input.addEventListener("keyup", calcFee)    
 )


function calcFee() {
  var valueA = document.getElementById("input-01").value;
  var valueB = document.getElementById("input-02").value;
  const capicity = valueA * 288;
  document.getElementById("calc-bottles").textContent = capicity;
  document.getElementById("calc-price").innerHTML =
    capicity * 3.2 * 12 * valueB;
}

is this you are looking for? it is only simple example as it has no error checking but it can be good starting point.


EDIT: here is a lightly refactored code

const [...inputs] = document.querySelectorAll(".w-input")

const in_1 = inputs[0]
const in_2 = inputs[1]
const bottles = document.querySelector("#calc-bottles");
const price = document.querySelector("#calc-price")

inputs.forEach(input => {
    input.addEventListener("keyup", calcFee) 
})


function calcFee() {
  const capicity = in_1.value * 288;
  const total =  capicity * 3.2 * 12 * in_2.value;
  bottles.textContent = capicity;
  price.textContent = total;
}

1 Like

Wow, thanks @Stan
It works! :+1::+1::+1:

I slightly modified to fit my case~

const [...inputs] = document.querySelectorAll(".custom-input");

const in_0 = inputs[0];
const in_1 = inputs[1];
const bottles = document.querySelector("#calc-bottles");
const price = document.querySelector("#calc-price");
let capicity = 0;
let total = 0;

inputs.forEach((input) => {
  input.addEventListener("keyup", calcFee);
});

function calcFee() {
  var trolly = in_0.value;
  var year = in_1.value;
  capicity = trolly * 288;
  var pretotal = (capicity * 3.2 * 12 * year) / 10;
  total = pretotal.toFixed(0) * 10;
  bottles.textContent = capicity.toFixed(0);
  price.textContent = total.toFixed(0);
}