How to move this inline JS to a file

Tags:



I have this (simplified) inline JS which i want to move into a js file. Trying to clean up inline JS and CSS

<td><input type="number" id="total" class="main-input" onkeyup="calculate(this.value)" /> </td>

in a js file i already moved the function

function calculate(total) {
   // I do some calculations here and it returns the values live(very important) into other <td>'s
}

but i struggle greatly to move the inline onkeyup event. So what i tried to do inside my js file was this:

totalValue = parseInt(document.getElementById("total").value);
document.getElementById("total").onkeyup = function() {calculate(totalValue)};

but it doesn’t work… it reads it as 0.

I tried with AddEventListener too.. no luck

Answer

Try this. Use addEventListener, I have write a simple code below, just to print in console on keyup.

document.getElementById("total").addEventListener('keyup' ,function() {console.log('func called')});
<td><input type="number" id="total" class="main-input"  /> </td>

Just for reference https://www.w3schools.com/jsref/met_element_addeventlistener.asp



Source: stackoverflow