I want to write a simple code. The program will alert the type of the device "input or output". this is the code:
<h1>Input or output device?</h1>
device name: <input type="text" id="device">
<br><br>
<script>
const x = document.getElementById("device").value;
</script>
<button onclick='alert(x === "mouse" ? "input device":"output device")'>Check now</button>
The code inside the <script>
executes only once when the page loads - therefore, the value of x
is going to be fixed during the existence of the page. This is the reason why x
doesn't change when anything is typed.
There are many solutions. One would be to add onChange
event to the input.
<input type="text" id="device" onChange="inputChanged()">
<script>
var x;
function inputChanged() {
x = document.getElementById("device").value;
}
</script>