I'm trying to create a live age counter which calculates & updates the age every second using setInterval(). It works with the predefined input but isn't working with the manual user input submitted through a date object. How to pass the input of type 'date' to the calculateAge() function I'm using.
//js file
function ageCalculator() {
function startCal() {
setInterval( function() {
calculateAge();
}, 1000);
}
function calculateAge() {
var nowDate = new Date();
// Example date of birth.
var dob = document.getElementById("age-value");
var dobDate = new Date(dob);
var str = (years +":"+months+":"+weeks+":"+days+":"+hours+":"+minutes+":"+seconds);
document.getElementById("age").innerHTML = str;
}
return {
startCal : startCal
}
}
var ageCalculatorInstance = ageCalculator();
//ageCalculatorInstance.startCal();
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Age calculator</title>
</head>
<body>
<div class="container">
<header>
<h1>Age calculator</h1>
</header>
<div class="input-age">
<label for="age-value">Enter your age</label>
<input id="age-value" type="date" />
<button type="submit" onclick="function startCal()">Calculate Age</button>
</div>
<div id="age">
</div>
</div>
<script src='js/script.js'></script>
</body>
</html>
This should give you the date entered by the user:
const input = document.getElementById("age-value").value;
const dateEntered = new Date(input);
Use document.getElementById("age-value"). value
and call the function as onclick="ageCalculatorInstance.startCal()"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.