还返回DOB而不是年龄

时间:2018-06-12 06:19:08

标签: jquery html

当我尝试更改DOB的日期时,年龄也会返回日期。 我希望自动将其显示为年龄

<div class="input-group">
    <div class="input-group-append datepicker date" data-date="<?php echo date('Y-m-d') ?>" data-date-format="yyyy-mm-dd">
    <span class="input-group-text" style="border-radius:0px;color: #008080"><b>Date of Birth<font color="red"> * </font></b></span>
    <input class="form-control" name="dob" type="text" required="true" value="dob" style="border-radius:0px" readonly >
    <span class="add-on input-group-text" style="border-radius:0px;background-color: white"><i class="nav-icon fa fa-calendar"></i></span>

    <span class="input-group-text" style="color: #008080"><b>Age</b></span>
    <input type="text" name="age" class="form-control" value="age" style="border-radius:0%;max-width: 80px" placeholder="Age" required="true" pattern=".{1,50}$" title="Input must not exceed 50 characters" readonly />

<script>
function computeAge(){
  var $age   = $(this).closest('.input-group');
  var birthDay = $group.find('input[name = "dob"]').val();
  var DOB = new Date(birthDay);
  var today = new Date();
  $age.find('input[name = "age"]').val(Math.floor((today.getTime() - 
  DOB.getTime()) / (1000 * 60 * 60 * 24 * 365.25)));
}
</script>
</div>

1 个答案:

答案 0 :(得分:0)

以下是工作演示:https://codepen.io/creativedev/pen/ERmPxN

$('#dob').datepicker();
$("#dob").change(function(){
   console.log($('#userage').val());
   var today = new Date();
    var birthDate = new Date($('#dob').val());
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
   return $('#userage').val(age);
});