I have an input field where users can input a number, and JavaScript calculates a result and displays it on the page. In order to have the best user experience, I want JavaScript to perform the calculation whenever the number in the field is changed. However, the “change” event works only when the input loses focus.
I have added “keyup” as a second event for the calculation to be performed, which covers many cases of user input. However, this is still not perfect, because the user could paste a value into the box or change the value in some other way (i.e. clicking the up and down arrows on compatible browsers).
Is there an event that fires whenever the value in the input changes, regardless of the focus of the input? Is there some other way to work around this problem? It seems like this would be the kind of thing that would have a thousand hits on Google, but I can’t seem to find anything.
My code:
function onLoadFunc(){
if(document.addEventListener){
document.getElementById("wm_buy_amt_input").addEventListener("keyup", wbCalculateOther, false);
document.getElementById("wm_buy_amt_input").addEventListener("change", wbCalculateOther, false);
}else if(document.attachEvent){
document.getElementById("wm_buy_amt_input").attachEvent("onkeyup", wbCalculateOther);
document.getElementById("wm_buy_amt_input").attachEvent("onchange", wbCalculateOther);
}
}
<input type="number" value="0" min="0" id="wm_buy_amt_input" />