You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery Datepicker填充日、月、年多个独立字段

解决jQuery Datepicker拆分日期到日/月/年独立字段的问题

你当前的代码问题在于重复声明altField和altFormat配置项,后面的配置会直接覆盖前面的,所以最终只有#annee字段会被填充。要实现日期拆分到三个独立字段,需要借助Datepicker的onSelect事件来手动处理日期的拆分与赋值。

正确实现代码

<head>
  <!-- 引入jQuery和jQuery UI依赖 -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
  
  <script>
    $(function() {
      $("#datepicker").datepicker({
        // 设置主日期输入框的显示格式
        dateFormat: "dd/mm/yy",
        // 选中日期时触发的事件
        onSelect: function(selectedDate) {
          // 将选中日期转为Date对象
          const date = new Date(selectedDate);
          // 处理日:确保两位数,不足补0
          const day = String(date.getDate()).padStart(2, '0');
          // 处理月:getMonth返回0-11,需+1后补0
          const month = String(date.getMonth() + 1).padStart(2, '0');
          // 获取完整年份
          const year = date.getFullYear();
          
          // 赋值到对应字段
          $("#jour").val(day);
          $("#mois").val(month);
          $("#annee").val(year);
        }
      });
    });
  </script>
</head>
<body>
  <p>Date: <input type="text" id="datepicker">&nbsp;<input type="text" id="jour" size="10" placeholder="日">&nbsp;<input type="text" id="mois" size="10" placeholder="月">&nbsp;<input type="text" id="annee" size="10" placeholder="年">&nbsp;</p>
</body>

关键说明

  • onSelect事件在用户选中日期时触发,参数selectedDate为选中的日期字符串,格式由dateFormat定义
  • 通过Date对象解析日期后,用getDate()、getMonth()+1、getFullYear()分别提取日、月、年
  • padStart(2, '0')保证日和月始终以两位数显示(如1号显示为"01",3月显示为"03")

内容的提问来源于stack exchange,提问作者Eric Eychenne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 16:25:21