在html中有如下标签

     身份证号:<input type="text" id="Gra_IDCard" onChange="IDCardChange()"/> <br/>
出生日期:<input type="date" id="Gra_BirthDate"/> <br/>
用户年龄:<input type="number" id="Gra_NameAge"/>

在js中方法

<script>
//身份证改变事件(孕妇)
var IDCardChange = function () {
//获取身份证号
var idCard = $('#Gra_IDCard').val();
//判断身份证长度
if (idCard.length == 18) {
//获取计算后出生日期
var birthDateStr = getBirthDate(idCard);
//设置出生日期
$('#Gra_BirthDate').val(birthDateStr); //获取当前的日期
var nowDateStr = getNowDate();
//获取计算后年龄(两个日期之间)
var age = getAge(birthDateStr, nowDateStr);
//设置年龄
$('#Gra_Age').val(age);
}
} //根据身份证号计算出生日期
var getBirthDate = function (IDCard)
{
//获取身份证号的年、月、日
var year = IDCard.substring(6, 10);
var month = IDCard.substring(10, 12);
var day = IDCard.substring(12, 14);
//拼接成出生日期
var birthDate = year + '-' + month + '-' + day;
return birthDate;
} //根据两个日期计算年龄(是否过生日)
var getAge = function (startDateStr, endDateStr)
{
//计算两个日期相差多少年
var startDate = new Date(startDateStr);
var endDate = new Date(endDateStr);
var yearNum = endDate.getFullYear() - startDate.getFullYear();
//获取两个日期(月+日)部分
var sStr = startDateStr.substring(5, 10);
var eStr = endDateStr.substring(5, 10);
//判断两个日期大小
//判断是否过生日
if (new Date(sStr) <= new Date(eStr)) {
return yearNum + 1;
}
else {
return yearNum;
}
} ///获取当前日期
var getNowDate = function () {
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1;
var day = d.getDate();
var dateStr = year + '-' + getFormatDate(month) + '-' + getFormatDate(day);
return dateStr;
} //格式化日期的月份或天数的显示(小于10,在前面增加0)
function getFormatDate(value) {
if (value == undefined || value == "") {
return '';
}
var str = value;
if (parseInt(value) < 10) {
str = '0' + value;
}
return str;
}
</script>

实现效果(改变身份证号时,带出出生日期和年龄)

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAe0AAABwCAIAAAC8Wb+FAAAJoUlEQVR4nO3cy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