Create an HTML Form: Start by creating an HTML form that includes an input field for the user to enter their birthdate and a submit button.
When you open the HTML file in a web browser, you will see the form. Enter a birthdate, submit the form, and it will display the calculated age.
DOCTYPE html> <html> <head> <title>Age Calculator</title> </head> <body> <form id="ageForm"> <label for="birthdate">Enter your birthdate:</label> <input type="date" id="birthdate" required> <input type="submit" value="Submit"> </form> <div id="result"></div> <script src="script.js"></script> </body> </html>
Create a JavaScript File: Create a JavaScript file (script.js) where you will handle the form submission and calculate the age.
document.getElementById('ageForm').addEventListener('submit', function(event) { event.preventDefault(); // Get the birthdate value from the form input const birthdate = document.getElementById('birthdate').value; // Calculate the age const age = calculateAge(birthdate); // Display the result document.getElementById('result').innerHTML = `Your age is ${age} years.`; }); function calculateAge(birthdate) { const today = new Date(); const birthdateDate = new Date(birthdate); let age = today.getFullYear() - birthdateDate.getFullYear(); const monthDiff = today.getMonth() - birthdateDate.getMonth(); if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthdateDate.getDate())) { age--; } return age; }
The HTML form contains an input field for the user to enter their birthdate and a submit button.
In the JavaScript file, an event listener is added to the form. When the form is submitted, it prevents the default behavior (which is to reload the page).
The calculateAge function takes a birthdate as input and returns the age in years.
Inside calculateAge, we create a new Date object for the current date (today) and another for the user's birthdate (birthdateDate).
We calculate the difference in years between the current year and the birth year, then adjust the age based on whether the birth month and day have already occurred this year.