JavaScript
<script type="text/javascript">
$(document).ready(function()
{
$('#dob').change(function()
{
var dob = new Date(document.getElementById('dob').value);
var today = new Date();
var age = Math.floor((today-dob)/(365.25*24*60*60*1000));
document.getElementById('age').value = age;
});
});
</script>
<div >
<label for="dob_label">Date of Birth</label></br>
<input type="date" name="dob" id="dob" required/>
</div>
<div >
<label for="age_label">age</label></br>
<input type="text" name="age" id="age" readonly/>
</div>
This is what I've tried for auto calculation of age in javaScript but seems that the input age is not responsive when I've pick a date on the dob input. Please let me know which part that I've missed out for this function.
CodePudding user response:
Check in the Run Code Snippet - Your code is working
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(document).ready(function()
{
$('#dob').change(function()
{
console.log("change");
var dob = new Date(document.getElementById('dob').value);
var today = new Date();
var age = Math.floor((today-dob)/(365.25*24*60*60*1000));
document.getElementById('age').value = age;
});
});
</script>
<div >
<label for="dob_label">Date of Birth</label></br>
<input type="date" name="dob" id="dob" required/>
</div>
<div >
<label for="age_label">age</label></br>
<input type="text" name="age" id="age" readonly/>
</div>
</body>
</html>