tutan
April 25, 2024, 1:23pm
1
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):
<script>
function bytton() {
window.alert(document.getElementById("wpo-option-5-28-23397").value * document.getElementById("wpo-option-5-29-23397").value);
}
</script>
<button type="button" onclick="bytton()">Calculate</button>
Will really appreciate any suggestions.
a2937
April 25, 2024, 1:30pm
2
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.
The change event is fired for , , and elements when the user modifies the element's value. Unlike the input event, the change event is not necessarily fired for each alteration to an element's value.
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.
Example:
<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