美文网首页
input输入框输入身份证号码,自动填充年月日

input输入框输入身份证号码,自动填充年月日

作者: 祈澈菇凉 | 来源:发表于2023-09-17 09:44 被阅读0次
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    
        </head>
        <body>
            <input type="text" placeholder="请输入身份证号" id="idCard">
        
            <input type="text" placeholder="请输入年" id="year">
            <input type="text" placeholder="请输入月" id="month">
            <input type="text" placeholder="请输入日" id="day">
            <script>
                $(document).ready(function() {
                    // 获取身份证号码输入框和三个 select 元素
                    const idCardInput = $('#idCard');
                    const yearSelect = $('#year');
                    const monthSelect = $('#month');
                    const daySelect = $('#day');
    
                    // 监听身份证号码输入框的输入事件
                    idCardInput.on('input', function() {
                        const idCardNumber = idCardInput.val();
    
                        // 提取身份证中的年、月、日
                        const year = idCardNumber.substr(6, 4);
                        let month = idCardNumber.substr(10, 2);
                        let day = idCardNumber.substr(12, 2);
    
                        // 去除月份和日期前的零
                        if (month.startsWith('0')) {
                            month = month.substr(1);
                        }
                        if (day.startsWith('0')) {
                            day = day.substr(1);
                        }
    
                        // 将提取的值赋值给对应的 select 元素
                        yearSelect.val(year);
                        monthSelect.val(month);
                        daySelect.val(day);
                    });
                });
            </script>
        </body>
    </html>
    
    

    通过$('#id')方式获取身份证号码输入框和三个select元素(年、月、日)。
    使用on('input', function() { ... })来监听身份证号码输入框的输入事件。

    当用户输入身份证号码时,代码会提取身份证号码中的年、月、日部分,并将其赋值给对应的select元素。

    在提取月份和日期时,代码还会去除前面可能存在的零。
    通过val()方法将提取的值赋给对应的select元素,实现选中对应的选项。

    相关文章

      网友评论

          本文标题:input输入框输入身份证号码,自动填充年月日

          本文链接:https://www.haomeiwen.com/subject/hypevdtx.html