I have made a calculator tool that has about 10 different text inputs for the user to complete before clicking the "calculate" button to run a function and return the calculated values. I want the function to run every time a text input is changed, rather than using a button. Here is a simple example to work with:
function calculate() {
//Inputs ("parseInt" converts string to Int)
var A = parseInt(document.getElementById("A").value);
var B = parseInt(document.getElementById("B").value);
var total = A*B;
//Output
document.getElementById("total").value = total;
};
<input type="text" id="A"> x
<input type="text" id="B">
<input type="button" onClick="calculate()" value="Calculate"> =
<output id="total"></output>
The above example has two text inputs that are multiplied when the button is clicked. What would be the best way to do this, so that the output is calculated every time a text input is changed? Keep in mind that the actual project has multiple text inputs.
Execute the function on oninput in both the text input as well:
function calculate() {
//Inputs ("parseInt" converts string to Int)
var A = parseInt(document.getElementById("A").value);
var B = parseInt(document.getElementById("B").value);
var total = A*B;
//Output
document.getElementById("total").value = total;
};
<input type="text" id="A" oninput="calculate()"> x
<input type="text" id="B" oninput="calculate()">
<input type="button" onClick="calculate()" value="Calculate"> =
<output id="total"></output>
OR: You might want to attach the event with forEach():
function calculate() {
//Inputs ("parseInt" converts string to Int)
var A = parseInt(document.getElementById("A").value);
var B = parseInt(document.getElementById("B").value);
var total = A*B;
//Output
document.getElementById("total").value = total;
};
var allTextInput = document.querySelectorAll('input[type=text]');
[...allTextInput].forEach(el => el.addEventListener('input', calculate));
<input type="text" id="A" oninput="calculate()"> x
<input type="text" id="B" oninput="calculate()">
<input type="button" onClick="calculate()" value="Calculate"> =
<output id="total"></output>
<input type="text" onInput="calculate()" id="A"> x
<input type="text" onInput="calculate()" id="B"> x
<input type="text" onInput="calculate()" id="C"> =
<output id="total"></output>
<script>
function calculate() {
//Inputs ("parseInt" converts string to Int)
var A = parseInt(document.getElementById("A").value);
var B = parseInt(document.getElementById("B").value);
var C = parseInt(document.getElementById("C").value);
var total;
if(isNaN(A)){
A=1;
}
if(isNaN(B)){
B=1;
}
if(isNaN(C)){
C=1;
}
total = A*B*C;
//Output
document.getElementById("total").value = total;
};
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With