Could someone kindly guide me on where I'm going wrong?
I am a budding developer and these concepts are fairly new to me. Can you offer your assistance?
Whenever I attempt to run my code, I encounter an error that reads "Uncaught ReferenceError: calc is not defined at HTMLButtonElement.onclick".
I aim to have the answer displayed within the div identified as "result" but unfortunately, it's not functioning as intended.
Here's the Markup:
<!DOCTYPE html>
<html>
<head>
<title>My First Calculator</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<form>
Value 1: <input type="text" id="value1">
Value 2: <input type="text" id="value2">
Operator:
<select id="operator">
<option value="add">Add</option>
<option value="sub">Subtract</option>
<option value="mul">Multiply</option>
<option value="div">Divide</option>
</select>
<button type="button" onclick="calc()">Calculate</button>
</form>
<div id="result"></div>
</body>
</html>
enter code here
Javascript Code:
function calc() {
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);
var op = document.querySelector("#operator").value;
var calculate;
if (op == "add") {
calculate = a + b;
} else if (op == "sub") {
calculate = a - b;
} else if (op == "mul") {
calculate = a * b;
} else if (op == "div") {
calculate = a / b;
}
document.getElementsByTagName("button")[0].addEventListener("click", calc);
}