jQuery UI DatePicker仅显示月份
我正在使用jQuerydateselect器来显示全部在我的应用程序的日历。 我想知道是否可以用它来显示月份和年份(2010年5月),而不是日历?
这是一个黑客(更新整个.html文件):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css"> <script type="text/javascript"> $(function() { $('.date-picker').datepicker( { changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'MM yy', onClose: function(dateText, inst) { $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1)); } }); }); </script> <style> .ui-datepicker-calendar { display: none; } </style> </head> <body> <label for="startDate">Date :</label> <input name="startDate" id="startDate" class="date-picker" /> </body> </html>
编辑 jsfiddle上面的例子: http : //jsfiddle.net/DBpJe/7755/
编辑2仅在单击“完成”button时将月份年份值添加到input框。 也允许删除input框的值,这是不可能在上面的字段http://jsfiddle.net/DBpJe/5103/
编辑3基于rexwolf的解决scheme更新了更好的解决scheme。
http://jsfiddle.net/DBpJe/5106
这段代码对我来说是完美无缺的:
<script type="text/javascript"> $(document).ready(function() { $(".monthPicker").datepicker({ dateFormat: 'MM yy', changeMonth: true, changeYear: true, showButtonPanel: true, onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).val($.datepicker.formatDate('MM yy', new Date(year, month, 1))); } }); $(".monthPicker").focus(function () { $(".ui-datepicker-calendar").hide(); $("#ui-datepicker-div").position({ my: "center top", at: "center bottom", of: $(this) }); }); }); </script> <label for="month">Month: </label> <input type="text" id="month" name="month" class="monthPicker" />
输出是:
@本克勒 ,这是完美的! 我做了一个小修改,以便多次使用dateselect器的单个实例按预期工作。 如果没有此修改,date将被错误地parsing,并且之前select的date不会突出显示。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css"> <script type="text/javascript"> $(function() { $('.date-picker').datepicker( { changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'MM yy', onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker('setDate', new Date(year, month, 1)); }, beforeShow : function(input, inst) { var datestr; if ((datestr = $(this).val()).length > 0) { year = datestr.substring(datestr.length-4, datestr.length); month = jQuery.inArray(datestr.substring(0, datestr.length-5), $(this).datepicker('option', 'monthNamesShort')); $(this).datepicker('option', 'defaultDate', new Date(year, month, 1)); $(this).datepicker('setDate', new Date(year, month, 1)); } } }); }); </script> <style> .ui-datepicker-calendar { display: none; } </style> </head> <body> <label for="startDate">Date :</label> <input name="startDate" id="startDate" class="date-picker" /> </body> </html>
上面的答案是相当不错的。 我唯一的抱怨是,一旦设定好,你就无法清除这个值。 另外我更喜欢使用扩展的jquery-like-a-plugin方法。
这对我来说是完美的:
$.fn.monthYearPicker = function(options) { options = $.extend({ dateFormat: "MM yy", changeMonth: true, changeYear: true, showButtonPanel: true, showAnim: "" }, options); function hideDaysFromCalendar() { var thisCalendar = $(this); $('.ui-datepicker-calendar').detach(); // Also fix the click event on the Done button. $('.ui-datepicker-close').unbind("click").click(function() { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); thisCalendar.datepicker('setDate', new Date(year, month, 1)); }); } $(this).datepicker(options).focus(hideDaysFromCalendar); }
然后像这样调用:
$('input.monthYearPicker').monthYearPicker();
<style> .ui-datepicker table{ display: none; }
<script type="text/javascript"> $(function() { $( "#manad" ).datepicker({ changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'yy-mm', onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker('setDate', new Date(year, month, 1)); }, beforeShow : function(input, inst) { if ((datestr = $(this).val()).length > 0) { actDate = datestr.split('-'); year = actDate[0]; month = actDate[1]-1; $(this).datepicker('option', 'defaultDate', new Date(year, month)); $(this).datepicker('setDate', new Date(year, month)); } } }); });
这将解决问题=)但是我想的时间格式yyyy毫米
只在FF4尝试
我今天有这个相同的需求,发现这在github上,使用jQueryUI和月份select器代替日历中的日历
这是我想出来的。 它隐藏日历而不需要额外的样式块,并添加一个清除button来处理单击input后无法清除值的问题。 也可以在同一页面上使用多个月份select器。
HTML:
<input type='text' class='monthpicker'>
JavaScript的:
$(".monthpicker").datepicker({ changeMonth: true, changeYear: true, dateFormat: "yy-mm", showButtonPanel: true, currentText: "This Month", onChangeMonthYear: function (year, month, inst) { $(this).val($.datepicker.formatDate('yy-mm', new Date(year, month - 1, 1))); }, onClose: function(dateText, inst) { var month = $(".ui-datepicker-month :selected").val(); var year = $(".ui-datepicker-year :selected").val(); $(this).val($.datepicker.formatDate('yy-mm', new Date(year, month, 1))); } }).focus(function () { $(".ui-datepicker-calendar").hide(); }).after( $("<a href='javascript: void(0);'>clear</a>").click(function() { $(this).prev().val(''); }) );
我需要两个字段(From&To)的月/年select器,当select一个时,Max / Min被设置在另一个字段上。 我有问题设置最大和最小…其他领域的date将被删除。 感谢上面的几个post…我终于明白了。 您必须按照特定的顺序设置选项和date。
看到这个小提琴的完整解决scheme: 月/年select@ JSFiddle
码:
var searchMinDate = "-2y"; var searchMaxDate = "-1m"; if ((new Date()).getDate() <= 5) { searchMaxDate = "-2m"; } $("#txtFrom").datepicker({ dateFormat: "M yy", changeMonth: true, changeYear: true, showButtonPanel: true, showAnim: "", minDate: searchMinDate, maxDate: searchMaxDate, showButtonPanel: true, beforeShow: function (input, inst) { if ((datestr = $("#txtFrom").val()).length > 0) { var year = datestr.substring(datestr.length - 4, datestr.length); var month = jQuery.inArray(datestr.substring(0, datestr.length - 5), "#txtFrom").datepicker('option', 'monthNamesShort')); $("#txtFrom").datepicker('option', 'defaultDate', new Date(year, month, 1)); $("#txtFrom").datepicker('setDate', new Date(year, month, 1)); } }, onClose: function (input, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $("#txtFrom").datepicker('option', 'defaultDate', new Date(year, month, 1)); $("#txtFrom").datepicker('setDate', new Date(year, month, 1)); var to = $("#txtTo").val(); $("#txtTo").datepicker('option', 'minDate', new Date(year, month, 1)); if (to.length > 0) { var toyear = to.substring(to.length - 4, to.length); var tomonth = jQuery.inArray(to.substring(0, to.length - 5), $("#txtTo").datepicker('option', 'monthNamesShort')); $("#txtTo").datepicker('option', 'defaultDate', new Date(toyear, tomonth, 1)); $("#txtTo").datepicker('setDate', new Date(toyear, tomonth, 1)); } } }); $("#txtTo").datepicker({ dateFormat: "M yy", changeMonth: true, changeYear: true, showButtonPanel: true, showAnim: "", minDate: searchMinDate, maxDate: searchMaxDate, showButtonPanel: true, beforeShow: function (input, inst) { if ((datestr = $("#txtTo").val()).length > 0) { var year = datestr.substring(datestr.length - 4, datestr.length); var month = jQuery.inArray(datestr.substring(0, datestr.length - 5), $("#txtTo").datepicker('option', 'monthNamesShort')); $("#txtTo").datepicker('option', 'defaultDate', new Date(year, month, 1)); $("#txtTo").datepicker('setDate', new Date(year, month, 1)); } }, onClose: function (input, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $("#txtTo").datepicker('option', 'defaultDate', new Date(year, month, 1)); $("#txtTo").datepicker('setDate', new Date(year, month, 1)); var from = $("#txtFrom").val(); $("#txtFrom").datepicker('option', 'maxDate', new Date(year, month, 1)); if (from.length > 0) { var fryear = from.substring(from.length - 4, from.length); var frmonth = jQuery.inArray(from.substring(0, from.length - 5), $("#txtFrom").datepicker('option', 'monthNamesShort')); $("#txtFrom").datepicker('option', 'defaultDate', new Date(fryear, frmonth, 1)); $("#txtFrom").datepicker('setDate', new Date(fryear, frmonth, 1)); } } });
如上所述,将其添加到样式块中:
.ui-datepicker-calendar { display: none !important; }
我结合了许多以上的好答案,并得出这个:
$('#payCardExpireDate').datepicker( { dateFormat: "mm/yy", changeMonth: true, changeYear: true, showButtonPanel: true, onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker('setDate', new Date(year, month, 1)).trigger('change'); }, beforeShow : function(input, inst) { if ((datestr = $(this).val()).length > 0) { year = datestr.substring(datestr.length-4, datestr.length); month = datestr.substring(0, 2); $(this).datepicker('option', 'defaultDate', new Date(year, month-1, 1)); $(this).datepicker('setDate', new Date(year, month-1, 1)); } } }).focus(function () { $(".ui-datepicker-calendar").hide(); $("#ui-datepicker-div").position({ my: "center top", at: "center bottom", of: $(this) }); });
这被certificate是可行的,但面对很多错误,所以我不得不在几个datepicker的地方打补丁:
if($.datepicker._get(inst, "dateFormat") === "mm/yy") { $(".ui-datepicker-calendar").hide(); }
patch1:在_showDatepicker:平滑隐藏;
patch2:在_checkOffset中:修正月份select器的位置(否则当字段位于浏览器底部时,偏移量检查closures)。
patch3:在closures的_hideDatepicker:否则当closuresdate字段会闪烁很短的时间,这是非常烦人的。
我知道我的解决办法很不好,但现在正在工作。 希望它有帮助。
是只是我还是这不工作,因为它应该在IE浏览器(8)? 点击完成后date会发生变化,但dateselect器会再次打开,直到您实际单击页面中的某个位置以将焦点放在input字段上。
我正在解决这个问题。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css"> <script type="text/javascript"> $(function() { $('.date-picker').datepicker( { changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'MM yy', onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker('setDate', new Date(year, month, 1)); } }); }); </script> <style> .ui-datepicker-calendar { display: none; } </style> </head> <body> <label for="startDate">Date :</label> <input name="startDate" id="startDate" class="date-picker" /> </body> </html>
有关: http : //www.mattkruse.com/javascript/calendarpopup/
select月份select示例
在挖掘jQueryUI.com datepicker后,这里是我的结论和答案你的问题。
首先,我会拒绝你的问题。 你不能使用jQueryUI datepicker来select月份和年份。 它不被支持。 它没有callback函数。
但是,你可以通过使用css来隐藏日子等等,只能显示月份和年份。而且我觉得没有意义,因为你需要点击date才能select一个date。
我可以说你只需要使用另一个dateselect器。 就像罗杰所说的那样。
我有dateselect器与月份select器混合的问题。 我就这样解决了
$('.monthpicker').focus(function() { $(".ui-datepicker-calendar").show(); }).datepicker( { changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'MM/yy', create: function (input, inst) { }, onClose: function(dateText, inst) { var month = 1+parseInt($("#ui-datepicker-div .ui-datepicker-month :selected").val()); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); } });
如果任何人也想为多个日历,这不是很难把这个function添加到jQuery UI。 与缩小search:
x+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+t+'">'+(/all|left/.test(t)&&C==0?c?f:n:"")+(
把这个添加在x前面
var accl = ''; if(this._get(a,"justMonth")) {accl = ' ui-datepicker-just_month';}
search
<table class="ui-datepicker-calendar
并用其replace
<table class="ui-datepicker-calendar'+accl+'
也search
this._defaults={
用它replace
this._defaults={justMonth:false,
对于CSS你应该使用:
.ui-datepicker table.ui-datepicker-just_month{ display: none; }
之后,所有完成只是去你想要的datepicker初始化函数,并提供设置变种
$('#txt_month_chart_view').datepicker({ changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'MM yy', justMonth: true, create: function(input, inst) { $(".ui-datepicker table").addClass("badbad"); }, onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker('setDate', new Date(year, month, 1)); } });
justMonth: true
是这里的关键:)
对BrianS近乎完美的回应进行了一些改进:
-
我已经在显示中设置了值,因为我认为它确实使得它在这种情况下更具可读性(尽pipe注意到我使用的是稍微不同的格式)
-
我的客户希望没有日历,所以我已经添加了一个显示/隐藏类别,而不影响任何其他dateselect器。 删除类是在一个计时器,以避免表闪烁备份dateselect器淡出,这似乎是非常明显的IE浏览器。
编辑:留下解决这个问题的一个问题是,没有办法清空dateselect器 – 清除该字段,然后单击,并使用所选date重新填充。
编辑2:我还没有设法解决这个很好(即没有添加一个单独的清除button旁边的input),所以结束了使用这个: https : //github.com/thebrowser/jquery.ui.monthpicker – 如果任何人都可以得到标准的用户界面,这将是惊人的。
$('.typeof__monthpicker').datepicker({ dateFormat: 'mm/yy', showButtonPanel:true, beforeShow: function(input, dpicker) { if(/^(\d\d)\/(\d\d\d\d)$/.exec($(this).val())) { var d = new Date(RegExp.$2, parseInt(RegExp.$1, 10) - 1, 1); $(this).datepicker('option', 'defaultDate', d); $(this).datepicker('setDate', d); } $('#ui-datepicker-div').addClass('month_only'); }, onClose: function(dt, dpicker) { setTimeout(function() { $('#ui-datepicker-div').removeClass('month_only') }, 250); var m = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var y = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker('setDate', new Date(y, m, 1)); } });
你也需要这个样式规则:
#ui-datepicker-div.month_only .ui-datepicker-calendar { display:none }
和其他许多人一样,我遇到了很多试图做到这一点的问题,只有解决scheme的组合,并最终做出一个很好的解决办法 , 给我一个解决scheme。
在这个线程中,我尝试了其他解决scheme的问题:
- 在dateselect器中select一个新date也会改变其他dateselect器的(内部)date,所以当你再次打开其他date时(或试图获得date),他们将有不同的date显示在他们分配的input-领域。
- dateselect器不会“记住”再次打开的date。
- 杂耍使用子串的date的代码,所以它不兼容所有格式。
- “我的月票”只是改变了closures它的input字段,而不是每当值被改变时。
- input字段未正确更新,如果您inputdate格式错误的inputstring,然后单击datepicker上的“closures”。
- 我不能有正常的dateselect器,它显示的日子,在monthpickers,不显示date在同一页上。
我终于find了解决所有这些问题的方法 。 前四个可以简单地通过小心你如何引用你的date和monthpickers在他们的内部代码,当然做一些手动更新你的采摘。 这可以在底部的实例中看到。 第五个问题可以通过添加一些自定义代码到datepicker函数来帮助。
注意:您不需要使用以下monthpicker脚本来解决您的正常dateselect器中的前三个问题。 只需使用本post底部附近的datepicker实例化脚本。
现在,要使用月份select器并修复最后一个问题,我们需要将dateselect器和月份select器分开。 我们可以得到less数几个jQuery-UI monthpicker插件之一,但有些缺乏本地化的灵活性/能力,有些缺lessanimation支持…所以,该怎么办? 从datepicker代码滚动你的“自己”! 这让你一个function齐全的monthpicker,具有datepicker的所有function,只是没有显示天。
我使用jQuery-UI v1.11.1代码,使用下面描述的方法提供了一个monthpicker js-script和伴随的CSS脚本 。 只需将这些代码片段分别复制到两个新文件monthpicker.js和monthpicker.css。
这是我经历的过程,克隆原来的dateselect器,并使其成为一个monthpicker
如果您不关心我是如何制作这些内容的,请滚动浏览此部分,然后直到“现在将dateselect器和月份select器添加到页面中”。
我已经把jquery-ui-1.11.1.js的所有javascript代码都归到了它们的datepicker,将它粘贴到一个新的js文件中,并replace了下面的string:
- “datepicker”==>“monthpicker”
- “Datepicker”==>“Monthpicker”
- “dateselect器”==>“月份select器”
- “dateselect器”==>“月份select器”
然后我删除了创build整个ui-datepicker-calendar div的for循环的一部分(使用CSS隐藏另一个解决scheme)。 这可以在_generateHTML:function(inst)中find。
find说:
"</div><table class='ui-datepicker-calendar'><thead>" +
从closuresdiv标签之后标记所有内容,直到( 不包括)它所在的行:
drawMonth++;
现在会不高兴,因为我们需要closures一些东西。 在closures之前的div标签之后,添加如下内容:
";
现在代码应该很好地缝合在一起。 这里有一个代码片段,显示你应该结束了什么:
...other code... calender += "<div class='ui-monthpicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" + (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") + (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers "</div>"; drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } ...other code...
然后,我将jquery-ui.css中与datepickers相关的代码复制/粘贴到一个新的CSS文件中,并replace下列string:
- “datepicker”==>“monthpicker”
现在将datepickers和monthpickers添加到页面!
以下JavaScript代码片段可以在页面上使用多个dateselect器和/或月份select器,而不会出现上述问题! 一般通过使用“$(this)”来修复。 很多 :)
第一个脚本是一个普通的dateselect器,第二个是“新”月份select器。
之后,它让你创build一些元素来清除input字段,从Paul Richards的答案中被盗。
我在monthpicker中使用“MM yy”格式,在datepicker中使用“yy-mm-dd”格式,但这与所有格式完全兼容 ,所以您可以随意使用任意一个。 只需更改'dateFormat'选项。 标准选项“showButtonPanel”,“showAnim”和“yearRange”当然是可选的,并可根据您的意愿定制。
添加dateselect器
Datepicker实例化。 这个从90年前到现在。 它可以帮助你保持input字段正确,特别是如果你设置了defaultDate,minDate和maxDate选项,但是如果你不这样做的话,它可以处理它。 它将与您select的任何dateFormat工作。
$('#MyDateTextBox').datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, showButtonPanel: true, showMonthAfterYear: true, showWeek: true, showAnim: "drop", constrainInput: true, yearRange: "-90:", minDate: new Date((new Date().getFullYear() - 90), new Date().getMonth(), new Date().getDate()), maxDate: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()), defaultDate: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()), onClose: function (dateText, inst) { // When onClose is called after we have clicked a day (and not clicked 'Close' or outside the datepicker), the input-field is automatically // updated with a valid date-string. They will always pass, because minDate and maxDate are already enforced by the datepicker UI. // This try is to catch and handle the situations, where you open the datepicker, and manually type in an invalid date in the field, // and then close the datepicker by clicking outside the datepicker, or click 'Close', in which case no validation takes place. try { // If datepicker can parse the date using our formatstring, the instance will automatically parse // and apply it for us (after the onClose is done). // If the input-string is invalid, 'parseDate' will throw an exception, and go to our catch. // If the input-string is EMPTY, then 'parseDate' will NOT throw an exception, but simply return null! var typedDate = $.datepicker.parseDate($(this).datepicker('option', 'dateFormat'), $(this).val()); // typedDate will be null if the entered string is empty. Throwing an exception will force the datepicker to // reset to the last set default date. // You may want to just leave the input-field empty, in which case you should replace 'throw "No date selected";' with 'return;' if (typedDate == null)throw "No date selected"; // We do a manual check to see if the date is within minDate and maxDate, if they are defined. // If all goes well, the default date is set to the new date, and datepicker will apply the date for us. var minDate = $(this).datepicker("option", "minDate"); var maxDate = $(this).datepicker("option", "maxDate"); if (minDate !== null && typedDate < minDate) throw "Date is lower than minDate!"; if (maxDate !== null && typedDate > maxDate) throw "Date is higher than maxDate!"; // We update the default date, because the date seems valid. // We do not need to manually update the input-field, as datepicker has already done this automatically. $(this).datepicker('option', 'defaultDate', typedDate); } catch (err) { console.log("onClose: " + err); // Standard behavior is that datepicker does nothing to fix the value of the input field, until you choose // a new valid date, by clicking on a day. // Instead, we set the current date, as well as the value of the input-field, to the last selected (and // accepted/validated) date from the datepicker, by getting its default date. This only works, because // we manually change the default date of the datepicker whenever a new date is selected, in both 'beforeShow' // and 'onClose'. var date = $(this).datepicker('option', 'defaultDate'); $(this).val($.datepicker.formatDate($(this).datepicker('option', 'dateFormat'), date)); $(this).datepicker('setDate', date); } }, beforeShow: function (input, inst) { // beforeShow is particularly irritating when initializing the input-field with a date-string. // The date-string will be parsed, and used to set the currently selected date in the datepicker. // BUT, if it is outside the scope of the minDate and maxDate, the text in the input-field is not // automatically updated, only the internal selected date, until you choose a new date (or, because // of our onClose function, whenever you click close or click outside the datepicker). // We want the input-field to always show the date that is currently chosen in our datepicker, // so we do some checks to see if it needs updating. This may not catch ALL cases, but these are // the primary ones: invalid date-format; date is too early; date is too late. try { // If datepicker can parse the date using our formatstring, the instance will automatically parse // and apply it for us (after the onClose is done). // If the input-string is invalid, 'parseDate' will throw an exception, and go to our catch. // If the input-string is EMPTY, then 'parseDate' will NOT throw an exception, but simply return null! var typedDate = $.datepicker.parseDate($(this).datepicker('option', 'dateFormat'), $(this).val()); // typedDate will be null if the entered string is empty. Throwing an exception will force the datepicker to // reset to the last set default date. // You may want to just leave the input-field empty, in which case you should replace 'throw "No date selected";' with 'return;' if (typedDate == null)throw "No date selected"; // We do a manual check to see if the date is within minDate and maxDate, if they are defined. // If all goes well, the default date is set to the new date, and datepicker will apply the date for us. var minDate = $(this).datepicker("option", "minDate"); var maxDate = $(this).datepicker("option", "maxDate"); if (minDate !== null && typedDate < minDate) throw "Date is lower than minDate!"; if (maxDate !== null && typedDate > maxDate) throw "Date is higher than maxDate!"; // We update the input-field, and the default date, because the date seems valid. // We also manually update the input-field, as datepicker does not automatically do this when opened. $(this).val($.datepicker.formatDate($(this).datepicker('option', 'dateFormat'), typedDate)); $(this).datepicker('option', 'defaultDate', typedDate); } catch (err) { // Standard behavior is that datepicker does nothing to fix the value of the input field, until you choose // a new valid date, by clicking on a day. // We want the same behavior when opening the datepicker, so we set the current date, as well as the value // of the input-field, to the last selected (and accepted/validated) date from the datepicker, by getting // its default date. This only works, because we manually change the default date of the datepicker whenever // a new date is selected, in both 'beforeShow' and 'onClose', AND have a default date set in the datepicker options. var date = $(this).datepicker('option', 'defaultDate'); $(this).val($.datepicker.formatDate($(this).datepicker('option', 'dateFormat'), date)); $(this).datepicker('setDate', date); } } }) //.after( // this makes a link labeled "clear" appear to the right of the input-field, which clears the text in it // $("<a href='javascript: void(0);'>clear</a>").click(function() { // $(this).prev().val(''); // }) //) ;
Adding a monthpicker
Include the monthpicker.js file and the monthpicker.css file in the page you want to use the monthpickers.
Monthpicker instantiation The value retrieved from this monthpicker, is always the FIRST day of the selected month. Starts at the current month, and ranges from 100 years ago and 10 years into the future.
$('#MyMonthTextBox').monthpicker({ dateFormat: 'MM yy', changeMonth: true, changeYear: true, showMonthAfterYear: true, showAnim: "drop", constrainInput: true, yearRange: "-100Y:+10Y", minDate: new Date(new Date().getFullYear() - 100, new Date().getMonth(), 1), maxDate: new Date((new Date().getFullYear() + 10), new Date().getMonth(), 1), defaultDate: new Date(new Date().getFullYear(), new Date().getMonth(), 1), // Monthpicker functions onClose: function (dateText, inst) { var date = new Date(inst.selectedYear, inst.selectedMonth, 1); $(this).monthpicker('option', 'defaultDate', date); $(this).monthpicker('setDate', date); }, beforeShow: function (input, inst) { if ($(this).monthpicker("getDate") !== null) { // Making sure that the date set is the first of the month. if($(this).monthpicker("getDate").getDate() !== 1){ var date = new Date(inst.selectedYear, inst.selectedMonth, 1); $(this).monthpicker('option', 'defaultDate', date); $(this).monthpicker('setDate', date); } } else { // If the date is null, we reset it to the defaultDate. Make sure that the defaultDate is always set to the first of the month! $(this).monthpicker('setDate', $(this).monthpicker('option', 'defaultDate')); } }, // Special monthpicker function! onChangeMonthYear: function (year, month, inst) { $(this).val($.monthpicker.formatDate($(this).monthpicker('option', 'dateFormat'), new Date(year, month - 1, 1))); } }) //.after( // this makes a link labeled "clear" appear to the right of the input-field, which clears the text in it // $("<a href='javascript: void(0);'>clear</a>").click(function() { // $(this).prev().val(''); // }) //) ;
而已! That's all you need to make a monthpicker.
I can't seem to make a jsfiddle work with this, but it is working for me in my ASP.NET MVC project. Just do what you normally do to add a datepicker to your page, and incorporate the above scripts, possibly by changing the selector (meaning $("#MyMonthTextBox")) to something that works for you.
我希望这可以帮助别人。
Links to pastebins for some extra date- and monthpicker setups:
-
Monthpicker working on the last day of the month . The date you get from this monthpicker will always be the last day of the month.
-
Two collaborating monthpickers ; 'start' is working on the first of the month, and 'end' is working on the last of the month. They are both restricted by each other, so choosing a month on 'end' which is before the selected month on 'start', will change 'start' to be the same month as 'end'. And vice versa. OPTIONAL: When selecting a month on 'start', the 'minDate' is set on 'end'. To remove this feature, comment out one line in onClose (read the comments).
-
Two collaborating datepickers ; They are both restricted by each other, so choosing a date on 'end' which is before the selected date on 'start', will change 'start' to be the same month as 'end'. And vice versa. OPTIONAL: When selecting a date on 'start', the 'minDate' is set on 'end'. To remove this feature, comment out one line in onClose (read the comments).
I liked the @user1857829 answer and his "extend-jquery-like-a-plugin approach". I just made a litte modification so that when you change month or year in any way the picker actually writes the date in the field. I found that I'd like that behaviour after using it a bit.
jQuery.fn.monthYearPicker = function(options) { options = $.extend({ dateFormat: "mm/yy", changeMonth: true, changeYear: true, showButtonPanel: true, showAnim: "", onChangeMonthYear: writeSelectedDate }, options); function writeSelectedDate(year, month, inst ){ var thisFormat = jQuery(this).datepicker("option", "dateFormat"); var d = jQuery.datepicker.formatDate(thisFormat, new Date(year, month-1, 1)); inst.input.val(d); } function hideDaysFromCalendar() { var thisCalendar = $(this); jQuery('.ui-datepicker-calendar').detach(); // Also fix the click event on the Done button. jQuery('.ui-datepicker-close').unbind("click").click(function() { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); thisCalendar.datepicker('setDate', new Date(year, month, 1)); thisCalendar.datepicker("hide"); }); } jQuery(this).datepicker(options).focus(hideDaysFromCalendar); }
Add one more simple solution
$(function() { $('.monthYearPicker').datepicker({ changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'M yy' }).focus(function() { var thisCalendar = $(this); $('.ui-datepicker-calendar').detach(); $('.ui-datepicker-close').click(function() { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); thisCalendar.datepicker('setDate', new Date(year, month, 1)); }); }); });
http://jsfiddle.net/tmnasim/JLydp/
特点 :
- display only month/year
- Adds the month year value to input box only on clicking of Done button
- No "reopen" behavior when click "Done"
————————————
another solution that work well for datepicker and monthpicker in the same page:(also avoid the bug of mutiple click on previous button in IE, that may occur if we use focus function)
JS fiddle link
I've had certain difficulties with the accepted answer and no other one could be used with a minimum effort as a base. So, I decided to tweak the latest version of the accepted answer until it satisfies at least minimum JS coding/reusability standards.
Here is a way much cleaner solution than the 3rd (latest) edition of the Ben Koehler 's accepted answer. Moreover, it will:
- work not only with the
mm/yy
format, but with any other including the OP'sMM yy
. - not hide the calendar of other datepickers on the page.
- not implicitly pollute the global JS object with the
datestr
,month
,year
etc variables.
一探究竟:
$('.date-picker').datepicker({ dateFormat: 'MM yy', changeMonth: true, changeYear: true, showButtonPanel: true, onClose: function (dateText, inst) { var isDonePressed = inst.dpDiv.find('.ui-datepicker-close').hasClass('ui-state-hover'); if (!isDonePressed) return; var month = inst.dpDiv.find('.ui-datepicker-month').find(':selected').val(), year = inst.dpDiv.find('.ui-datepicker-year').find(':selected').val(); $(this).datepicker('setDate', new Date(year, month, 1)).change(); $('.date-picker').focusout(); }, beforeShow: function (input, inst) { var $this = $(this), // For the simplicity we suppose the dateFormat will be always without the day part, so we // manually add it since the $.datepicker.parseDate will throw if the date string doesn't contain the day part dateFormat = 'd ' + $this.datepicker('option', 'dateFormat'), date; try { date = $.datepicker.parseDate(dateFormat, '1 ' + $this.val()); } catch (ex) { return; } $this.datepicker('option', 'defaultDate', date); $this.datepicker('setDate', date); inst.dpDiv.addClass('datepicker-month-year'); } });
And everything else you need is the following CSS somewhere around:
.datepicker-month-year .ui-datepicker-calendar { display: none; }
而已。 Hope the above will save some time for further readers.
I know it's a little late response, but I got the same problem a couple of days before and I have came with a nice & smooth solution. First I found this great date picker here
Then I've just updated the CSS class (jquery.calendarPicker.css) that comes with the example like this:
.calMonth { /*border-bottom: 1px dashed #666; padding-bottom: 5px; margin-bottom: 5px;*/ } .calDay { display:none; }
The plugin fires an event DateChanged when you change anything, so it doesn't matter that you are not clicking on a day (and it fits nice as a year and month picker)
希望它有帮助!
I also needed a month picker. I made a simple one with year on header and 3 rows of 4 months below. Check it out: Simple monthyear picker with jQuery .
I tried the various solutions provided here and they worked fine if you simply wanted a couple of drop downs.
The best (in appearance etc) 'picker' ( https://github.com/thebrowser/jquery.ui.monthpicker ) suggested here is basically a copy of an old version of jquery-ui datepicker with the _generateHTML rewritten. However, I found it no longer plays nicely with current jquery-ui (1.10.2) and had other issues (doesn't close on esc, doesn't close on other widget opening, has hardcoded styles).
Rather than attempt to fix that monthpicker and rather than reattempt the same process with the latest datepicker, I went with hooking into the relevant parts of the existing date picker.
This involves overriding:
- _generateHTML (to build the month picker markup)
- parseDate (as it doesn't like it when there's no day component),
- _selectDay (as datepicker uses .html() to get the day value)
As this question is a bit old and already well answered, here's only the _selectDay override to show how this was done:
jQuery.datepicker._base_parseDate = jQuery.datepicker._base_parseDate || jQuery.datepicker.parseDate; jQuery.datepicker.parseDate = function (format, value, settings) { if (format != "M y") return jQuery.datepicker._hvnbase_parseDate(format, value, settings); // "M y" on parse gives error as doesn't have a day value, so 'hack' it by simply adding a day component return jQuery.datepicker._hvnbase_parseDate("d " + format, "1 " + value, settings); };
As stated, this is an old question, but I found it useful so wanted to add feedback with an alterantive solution.
for a monthpicker, using JQuery v 1.7.2, I have the following javascript which is doing just that
$l("[id$=txtDtPicker]"). monthpicker ({
showOn: "both",
buttonImage: "../..http://img.dovov.comCalendar.png",
buttonImageOnly: true,
pattern: 'yyyymm', // Default is 'mm/yyyy' and separator char is not mandatory
monthNames: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez']
});
Everyone here is getting value of month , year like this,
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var month = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
But just now I'm facing issue while fetching values from >
and <
. Because It give us value of selected value in dropdown so it provides us old
value not new
values.
So, As per the document of Jquery UI :- http://api.jqueryui.com/datepicker/ . We can directly fetch year , month from function. For other values like day
etc. we can easily access them through inst object of jqueryUI
function. We can access inst like below,
var day = inst.selectedDay;
So, Using onChangeMonthYear
we can get current month , year and day values directly from function so no need to work out for selected value.
HTML :-
<input type='text' class='monthpicker'>
Script :-
$( function() { $(".monthPicker").datepicker({ dateFormat: 'MM yy', changeMonth: true, changeYear: true, showButtonPanel: true, beforeShow: true, onChangeMonthYear: function(year , month , inst) { setTimeout(function() { $('.ui-datepicker-calendar').hide(); }); var day = inst.selectedDay; month = month; year = year; var current_date = year + "-" + month + "-" + day ; } }); $(".monthPicker").focus(function () { $(".ui-datepicker-calendar").hide(); $("#ui-datepicker-div").position({ my: "center top", at: "center bottom", of: $(this) }); }); });
Note :- It can be useful when we want inline monthpicker. Just replace input field to division and we can use it inline while using inline make sure you are using onChangeMonthYear
,
For Inline MonthPicker :-
<div class="monthpicker"> </div>
Use onSelect
call back and remove the year portion manually and set the text in the field manually