【问题标题】:jQuery month/year picker not showing month/year in input on making a selectionjQuery 月/年选择器在进行选择时未在输入中显示月/年
【发布时间】:2017-07-01 08:59:44
【问题描述】:

我正在使用 jquery datepicker,我只需要一个月和一年。当我点击输入字段时,月份和年份选择器弹出就好了。问题是当我选择任何月份或年份时,更新的数据不会反映在输入字段中,除非我单击页面上的其他位置。

这就是我显示选择器的方式

$(function () {
    $(".datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: "-100:+0",
        dateFormat: 'MM yy',
        onClose: function (dateText, inst) {
            $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
        }
    });
});

我在这里做错了什么?只要我点击任何月份或年份,我只需要输入字段来反映更新的选择。

【问题讨论】:

  • 使用 onSelect 代替 onCloase

标签: jquery datepicker jquery-ui-datepicker


【解决方案1】:

使用onChangeMonthYear 而不是onClose

onChangeMonthYear 当日期选择器移动到新的月份和/或年份时调用。该函数接收选定的年、月 (1-12) 和 datepicker 实例作为参数。 this 指的是关联的输入字段。

$(function () {
    $(".datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: "-100:+0",
        dateFormat: 'MM yy',
        onChangeMonthYear: function (year,month, inst) {
            $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
        }
    });
});

$(function () {
        $(".datepicker").datepicker({
            changeMonth: true,
            changeYear: true,
            yearRange: "-100:+0",
            dateFormat: 'MM yy',
            onChangeMonthYear: function (year,month, inst) {
                $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1)); console.log(inst.selectedYear,inst.selectedMonth);
            }
        });
    });
<input class="datepicker" type="text" /><br />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

【讨论】:

  • onSelect 不起作用,当我在字段外单击时,onClose 至少显示了选定的数据,但 onSelect 没有执行任何操作
  • 非常感谢您的帮助。
  • 很高兴帮助你@Saadia
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多