While writing a small demo, I accidentally discovered that directly assigning a variable to the value attribute can result in not being able to retrieve the data or getting the desired content. In JavaScript, you cannot define the value attribute as a variable.
Let's first look at a piece of code:
<input type="text"" id="a">
<span>*</span>
<input type="text" id="b">
<input type="button" value="=" onclick="beto()">
<input type="text" id="sub" disabled>
<script>
function beto() {
var a = document.getElementById('a').value
var b = document.getElementById('b').value
var sub = document.getElementById('sub').value
sub = a + b
}
</script>
At first glance, the logic seems fine. It retrieves the values of 'a' and 'b', performs multiplication, and then outputs the result in 'sub'.
However, when running it in a browser, there is no response at all.
Why is that?
(Pretend to think for five minutes...)
It's because 'sub.value' cannot be directly assigned in a variable.
// First, define the input field with id 'sub'
var sub = document.getElementById('sub')
// Then, directly use sub.value in the calculation
sub.value = a * b
Here's a simple calculator that you can use when writing demos:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Calculator</title>
</head>
<body>
<input type="text"" id="a">
<select id="c">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" id="b">
<input type="button" value="=" onclick="beto()">
<input type="text" id="sub" disabled>
<script>
function beto() {
var a = document.getElementById('a').value
var b = document.getElementById('b').value
var c = document.getElementById('c').value
var sub = document.getElementById('sub')
switch(c) {
case "+":
sub.value = parseInt(a) + parseInt(b);
break;
case "-":
sub.value = parseInt(a) - parseInt(b);
break;
case "*":
sub.value = parseInt(a) * parseInt(b);
break;
case "/":
sub.value = parseInt(a) / parseInt(b);
break;
}
}
</script>
</body>
</html>