我想使用日期选择器在表单中自动填写我的年龄。当我使用日期选择器将生日放在出生日期表单上时,它应该自动填充表单中的年龄,然后它会自动确定其年龄。例如,我的生日是 1996 年 10 月 17 日,今天是 2017 年 7 月 30 日,因此表单将自动填充,如下所示: 20年9个月13天。
<!--html form-->
<input type="date" name="birthday"> 10/17/1996
<input type="text" name="Years"> 20 years
<input type="text" name="m"> 9 months
<input type="text" name="d"> 13 days
<!--script right here-->
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var Years = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
Years--;
}
return Years;
}
最佳答案
你可以像下面这样做:-
$(document).ready(function(){
$('input[type="date"]').on('mouseout',function(){
getAge($(this).val());
});
});
function getAge(dateString) {
if(dateString!==''){
d1 = new Date();
d2 = new Date(dateString);
diff = new Date(
d1.getFullYear()-d2.getFullYear(),
d1.getMonth()-d2.getMonth(),
d1.getDate()-d2.getDate()
);
$('input[name="Years"]').val(diff.getYear()+" Year(s)");
$('input[name="m"]').val(diff.getMonth()+" Month(s)");
$('input[name="d"]').val(diff.getDate()+" Day(s)");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" name="birthday"><br/><br/>
<input type="text" name="Years"><br>
<input type="text" name="m"><br>
<input type="text" name="d"><br>
关于javascript - 如何通过自动填充表格来获取以年、月和日为单位的年龄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45394870/