You have not assigned a class- or id-name with ‘operator’, so it can not find that element.
Solution 1 :
Problem :
I’m making a calculator. Inspector tells me it cannot read the property of value
at Line 4 of my JS.
I’ve gone through line by line and I can’t figure out what I’m doing wrong.
I am following this tutorial from mmtutus on YouTube.
I’ve gone through each line and my code is identical to his.
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 == "min") {
calculate = a - b;
} else if (op == "div") {
calculate = a / b;
} else if (op == "mul") {
calculate = a * b;
}
document.querySelector("#result").innerHTML = calculate;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form>
Value 1: <input type="text" id="value1" /> Value 2:
<input type="text" id="value2" /> Operator:
<select>
<option value="add"> Add </option>
<option value="min"> Subtract </option>
<option value="div"> Divide </option>
<option value="mul"> Multiply </option>
</select>
<button type="button" onclick="calc()">Calculate</button>
</form>
<div id="result"></div>
</body>
<script src="main.js"></script>
</html>
Could you help me to find the root of my issue?
Comments
Comment posted by VLAZ
document.querySelector("#operator")
Comment posted by EugenSunic
var op = document.querySelector("#value2").value;
Comment posted by Barmar
You need
Comment posted by EugenSunic
@Barmar did you just watch that youtube video?
Comment posted by Barmar
It’s at 05:00 in the video