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 content that is not what we want. In JavaScript, you cannot casually define the value attribute as a variable.
Let's take a 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, nothing happens at all.
Why is that?
(Pretend to think for five minutes...)
Because sub.value
cannot be directly defined in a variable.
// First, define the input field with the id 'sub'
var sub = document.getElementById('sub')
// Then, use sub.value directly 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>