js从身份证号中获取出生日期和性别

今天,在做移动端的项目中,按照设计稿的要求,是可以让用户自己输入出生日期的,我还很认真的用了刚刚知道的html5表单的日期类型,本想着终于不用日期插件就可以实现用户选择自己的出生日期了,可结果老大说,把这个表单去掉,要做成从身份证号里边读取用户的出生日期。好吧,高兴了一半,结果...。唉,没办法,只能按照领导的要求来做啊,于是就有了下边的从身份证号中获取出生日期和性别的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.min.js"></script>
</head>
<body>	
<input type="tel" id="js_Idcard">
<span id="js_birthday"></span>
<script>
    $(function(){
        function GetBirthdatByIdNo(iIdNo){
            var tmpStr = "";
            var birthday = $("#js_birthday");

            iIdNo = $.trim(iIdNo);

            if(iIdNo.length == 15){
                tmpStr = iIdNo.substring(6, 12);
                tmpStr = "19" + tmpStr;
                tmpStr = tmpStr.substring(0, 4) + "-" + tmpStr.substring(4, 6) + "-" + tmpStr.substring(6);
                sexStr = parseInt(iIdNo.substring(14, 1),10) % 2 ? "男" : "女";
                birthday.text(sexStr + tmpStr);
            }else{
                tmpStr = iIdNo.substring(6, 14);
                tmpStr = tmpStr.substring(0, 4) + "-" + tmpStr.substring(4, 6) + "-" + tmpStr.substring(6);
                sexStr = parseInt(iIdNo.substring(17, 1),10) % 2 ? "男" : "女";
                birthday.text(sexStr + tmpStr);
            }
        }

	$("#js_Idcard").blur(function(){
		GetBirthdatByIdNo($(this).val());
	});
});		
</script>
</body>
</html>

另一种从身份证号中获取性别的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.min.js"></script>
</head>

<body>	
<input type="tel" id="js_Idcard">
<span id="js_birthday"></span>
<script>
    $(function(){
        function go(){
         var id = $("#js_Idcard").val();
         var last = id[id.length - 2];

         if(last % 2 != 0){
             $("#js_birthday").text("男");
         }else{
             $("#js_birthday").text("女");
         }
     }

     $("#js_Idcard").blur(function(){
        go();
     });
});		
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/tnnyang/p/5130407.html