(Js) Multiply 2 numbers (in inputs) realtime

Hi guys,

I’am trying to multiply 2 numbers situated in inputs realtime. I have a woocommerce+wordpress product page and some of the products have weight and height options that user needs to set. I want to multiply this values realtime with js.

<input type="number" id="wpo-option-5-28-23397" name="wpo-option[option-28]" value="1" data-price-type="no_cost" data-price-amount="0" min="1" max="100" step="1">
<input type="number" id="wpo-option-5-29-23397" name="wpo-option[option-29]" value="1" data-price-type="no_cost" data-price-amount="0" min="1" max="100" step="1" required="">

The following code works but after clicking the button (my idea is to be realtime):

 function bytton() {    
 window.alert(document.getElementById("wpo-option-5-28-23397").value * document.getElementById("wpo-option-5-29-23397").value);
<button type="button" onclick="bytton()">Calculate</button>

Will really appreciate any suggestions.

I would recommend to use the onchange event on both your height and weight input elements. That is literally as close to real-time as you can get.

In addition to what @a2937 said,

you can use the event input in your event listener.

The difference between input and change events is that

input triggers immediately when the input value changes due to user interaction.
change is the same but it triggers after the element loses focus meaning that the user has finished interacting with it.


<input id="first" type="number">
<input id="second" type="number">
<div id="result"></div>
const input1 = document.getElementById("first");
const input2 = document.getElementById("second");
const result = document.getElementById("result");

function calculate(){
    result.textContent = input1.value * input2.value;

input1.addEventListener('input', calculate);
input2.addEventListener('input', calculate)

try it with input as the event then change it to change so you can see the difference and decide which is best suited for your conditions.

1 Like

Thank you very much! :trophy::muscle::pray: