我想用日期选择器自动填写我的年龄。当我使用日期选择器将生日放在生日表单上时,它应该自动填充表单中的年龄,然后它将自动确定它的年龄。例如,我的生日是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;
}发布于 2017-07-29 23:19:49
你可以这样做:-
$(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>
https://stackoverflow.com/questions/45394870
复制相似问题