age calculation in jquery


In this section, We will get age using the date of birth and current date using JQuery. Here we are using input type date for selecting Date. In HTML page we are using two input parameters such as first Date parameter is DateOfBirth and last one for showing age. Here's an example:


<span>
                        <strong>Date Of Birth*</strong><br />
                        <input type="date" id="DateOfBirth" name="DateOfBirth" value="" size="40" class="form-control" />
                    </span>

  <span>
                        <strong>Age*</strong><br />
                        <input type="text" id="Age" name="Age" value="" size="40" class="form-control" placeholder="Enter Age" disabled="disabled" />
                    </span>


Add jquery package in your solution and give that script reference in your HTML page. Like below script reference

<script src="~/Scripts/jquery-3.0.0.min.js"></script>

Otherwise you can add direct link of jquery script reference file. Like below script reference

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

Now write script for getting age using date of birth.

<script src="~/Scripts/jquery-3.0.0.min.js"></script>
<script>
    $(document).ready(function () {
$('#DateOfBirth').change(function () {
            var now = new Date();   //Current Date
            var past = new Date($('#DateOfBirth').val());  //Date of Birth
            if (past > now) {
                alert('Entered Date is Greater than Current Date');
                return false;
            }
            var nowYear = now.getFullYear();  //Get current year
            var pastYear = past.getFullYear();//Get Date of Birth year
            var age = nowYear - pastYear;  //calculate the difference
            $('#Age').val(age);
        })
})
</script>

Output :



Like this we will get our required result. and also follow this above procedure in your HTML page and you will also get your required result.

Post a Comment

0 Comments