【问题标题】:How to get date when selecting year and month in datepicker在日期选择器中选择年份和月份时如何获取日期
【发布时间】:2021-10-29 07:57:48
【问题描述】:

有没有办法在不点击完成按钮的情况下自动获取选择年份和月份的日期?

$(function() {
  $('.date-picker, .to').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy-mm-dd',
    onClose: function(dateText, inst) {
      $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
      $('#to').datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth + 1, 0));
    }
  });
});
.ui-datepicker-calendar {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<label for="startDate">Year/Month :</label>
<input name="startDate" id="startDate" class="date-picker" />
<input name="startDate" id="to" class="to" />

【问题讨论】:

  • 首先,您需要包含jquery 脚本,因为您使用的是jQuery 选择器$,以及jquery-ui 脚本,因为您使用的是datepicker,一个jQuery UI 小部件.这些脚本的 CDN 可以在这里找到cdnjs.com
  • 您的意思是喜欢使用onChangeMonthYear 事件?阅读文档是一个好习惯。

标签: javascript jquery jquery-ui datepicker


【解决方案1】:

考虑以下示例。

$(function() {
  function setDate(target, year, month, string) {
    var myDate;
    if ($(target).is("#first")) {
      day = 1;
      myDate = $.datepicker.parseDate("yy-mm-dd", year + "-" + month + "-01");
    } else {
      myDate = new Date(year, month, 0);
    }
    if (string) {
      $(target).val($.datepicker.formatDate("yy-mm-dd", myDate));
    } else {
      $(target).datepicker("setDate", myDate);
    }
  }

  $('.date-picker').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy-mm-dd',
    onChangeMonthYear: function(yy, mm) {
      setDate(this, yy, mm, true);
    },
    onClose: function(dateText, inst) {
      if ($(this).is("#first")) {
        setDate("#last", inst.selectedYear, inst.selectedMonth + 1, true);
      }
    }
  });
});
.ui-datepicker-calendar {
  display: none;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<label for="startDate">Year/Month :</label>
<input id="first" class="date-picker" />
<input id="last" class="date-picker" />

如果用户更改了他们想要的月份和年份,然后点击离开,这将填充该字段,就像您在 onClose 中所做的一样。

【讨论】:

  • 谢谢。根据您的回答,我已经创建了我想要的功能。此外,我想默认禁用第二个输入框,并在第一个输入框中输入日期时删除禁用。有什么办法吗?
  • @leesuccess 是的。
猜你喜欢
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 2021-12-15
  • 2011-05-04
相关资源
最近更新 更多