So for a class project I have to make this simple calculator, which was very easy to do. However, I'm required to define my event listeners in JavaScript instead of using something like: onclick="compute()"
But I need the result of my calculator to update whenever I change a value in my field or select any of the radio buttons. How can I do this? The code I have now is not working.
<script>
function compute(){
var functionSelected = document.getElementsByName("function");
var valueOne = Number(document.getElementById("fielda").value);
var valueTwo = Number(document.getElementById("fieldb").value);
var ans = 0;
if(functionSelected[0].checked){
ans = (valueOne+valueTwo);
}
if(functionSelected[1].checked){
ans = (valueOne-valueTwo);
}
if(functionSelected[2].checked){
ans = (valueOne*valueTwo);
}
if(functionSelected[3].checked){
ans = (valueOne/valueTwo);
}
if(ans>=9007199254740992){
document.getElementById("solution").textContent = "ERROR NUMBER TO LARGE TO BE COMPUTED";
}
else{
document.getElementById("solution").textContent = "Equals: " + ans;
}
}
document.getElementById("fielda").addEventListener("change", compute(), false);
document.getElementById("fieldb").addEventListener("change", compute(), false);
document.getElementByName("function").onclick = compute();
</script>
</head>
<body>
<p>
<input type="number" id="fielda"/><br />
<input type="number" id="fieldb"/><br />
<label><input name="function" type="radio" value="add"/> Add</label><br />
<label><input name="function" type="radio" value="subtract"/> Subtract</label><br />
<label><input name="function" type="radio" value="multiply"/> Multiply</label><br />
<label><input name="function" type="radio" value="divide"/> Divide</label><br />
</p>
<p>
<output id="solution">Solution Will Appear Here</output>
</p>
</body>