Search code examples
javascriptjqueryhtmlcalc

Function runs when any text input is changed


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.


Solution

  • Bind the elements change, keyup and mouseup events to trigger your calculate function.

    I'd recommend a couple of loops and addEventListener:

    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;
    };
    
    for (var elm of [document.getElementById("A"), document.getElementById("B"), document.getElementById("Calculate")]) {
      for (var st of ['change', 'keyup', 'mouseup', 'click']) {
        elm.addEventListener(st, calculate)
      }
    }
    <input type="number" id="A"> x
    <input type="number" id="B">
    <input type="button" id="Calculate" value="Calculate"> =
    <output id="total"></output>