HTML code with JavaScript to calculate age based on the birthdate
Here's the HTML code with JavaScript to calculate age based on the birthdate:
<!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>
<script>
function calculateAge() {
var birthDate = document.getElementById("birthDate").value;
var birthYear = new Date(birthDate).getFullYear();
var currentYear = new Date().getFullYear();
var age = currentYear - birthYear;
// Check the month and day in case the birthday hasn't occurred yet this year
var birthMonth = new Date(birthDate).getMonth();
var currentMonth = new Date().getMonth();
if (currentMonth < birthMonth || (currentMonth === birthMonth && new Date().getDate() < new Date(birthDate).getDate())) {
age--;
}
document.getElementById("result").innerHTML = "The person's age is: " + age + " years";
}
</script>
</head>
<body>
<h2>Age Calculator</h2>
<label for="birthDate">Birthdate:</label>
<input type="date" id="birthDate" required>
<button onclick="calculateAge()">Calculate Age</button>
<p id="result"></p>
</body>
</html>
How it works:
- The user inputs their birthdate in the date field.
- Upon clicking the button, JavaScript calculates the age based on the year, month, and day.
- The calculated age is displayed at the bottom of the page.
Let me know if you'd like to modify or add anything!
Comments
Post a Comment