'why input value cannot be access inside function in javascript [duplicate]
Why the variable is empty when accessing inside a function? Please see my code below
var age = document.getElementById('ageValue').value
function getAge() {
document.getElementById('age').innerHTML = 'Your age is: ' + age
}
<div id="age"></div>
<input type="text" id="ageValue">
<button type="button" onclick="getAge()">Show Age</button>
Solution 1:[1]
Put the reading the age part inside the function.
function getAge() {
var age = document.getElementById('ageValue').value;
document.getElementById('age').innerHTML = 'Your age is: ' + age
}
<div id="age"></div>
<input type="text" id="ageValue">
<button type="button" onclick="getAge()">Show Age</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LearningEveryday |
