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>
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>