Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript .change(function() calculate age based on date

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 class="input-field col  s12">
   <label for="dob_label">Date of Birth</label></br>
   <input type="date" name="dob" id="dob" required/>
</div>

<div class="input-field col  s12">
   <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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 class="input-field col  s12">
   <label for="dob_label">Date of Birth</label></br>
   <input type="date" name="dob" id="dob" required/>
</div>

<div class="input-field col  s12">
   <label for="age_label">age</label></br>
   <input type="text" name="age" id="age" readonly/>
</div>

</body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading