我正在使用 jQuery 日期选择器在我的应用程序中显示日历。我想知道我是否可以用它来显示月份和年份(2010 年 5 月)而不是日历?
28 回答
这是一个 hack(用整个 .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 仅在单击完成按钮时将月份年份值添加到输入框。还允许删除输入框值,这在上述字段http://jsfiddle.net/DBpJe/5103/中是不可能的
EDIT 3
根据 rexwolf 的解决方案更新了更好的解决方案。
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" />
输出是:
@Ben Koehler,太棒了!我做了一个小的修改,以便多次使用日期选择器的单个实例可以按预期工作。如果不进行此修改,则会错误地解析日期,并且不会突出显示先前选择的日期。
<!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>
上面的答案都很好。我唯一的抱怨是,一旦设置了值,您就无法清除它。我也更喜欢extend-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));
}
}
});
});
这将解决问题 =) 但我想要 timeFormat yyyy-mm
虽然只在FF4中尝试过
我今天也有同样的需求,并在 github 上找到了这个,它与 jQueryUI 一起使用,并且有月份选择器代替日历中的天数
这就是我想出的。它隐藏了日历而不需要额外的样式块,并添加了一个清除按钮来处理单击输入后无法清除值的问题。也可以很好地与同一页面上的多个月份选择器一起使用。
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('');
})
);
像许多其他人一样,我在尝试这样做时遇到了许多问题,只有发布的解决方案的组合,以及最终使其完美的大黑客,让我找到了一个适用于所有日期格式和本地化的解决方案,就像正常的日期选择器。
我尝试过的此线程中其他解决方案的问题:
- 在日期选择器中选择一个新日期,也会更改其他日期选择器的(内部)日期,因此当您再次打开其他日期选择器(或尝试获取他们的日期)时,它们的日期将与分配的输入中显示的日期不同-场地。
- 日期选择器在再次打开时不会“记住”日期。
- 用于处理日期的代码使用子字符串,因此它不兼容所有格式。
- 如果您为日期输入格式错误的输入字符串,然后单击日期选择器上的“关闭”,则输入字段未正确更新。
- 月份选择器仅在关闭时更改输入字段,而不是在更改值时更改。
- 您不能将显示日期的普通日期选择器与不显示日期的月份选择器放在同一页面上。
我终于找到了解决所有这些问题的方法,即使是在原来的日期选择器中!
注意:您不需要使用以下monthpicker 脚本来修复普通jQuery datepickers中的前四个问题。只需使用本文后面的Datepicker 实例化脚本。问题 5 和 6 仅与我尝试过的不同月份选择器解决方案有关。
问题 1-3 和 5 与如何在其内部代码中引用日期和月份选择器有关,确保它们不会干扰其他日期和月份选择器,以及选择器的一些手动更新。您可以在下面的实例化示例中看到这一点。第四个问题是通过向 datepicker 函数添加一些自定义代码来解决的(参见示例中的注释,尤其是关于 onClose)。
对于第六个也是最后一个问题,仅与使用月份选择器和日期选择器有关,我们只需将日期选择器和月份选择器正确分开即可。
那么,为什么不从那里获得为数不多的自定义 jQuery-UI 月份选择器插件之一呢?我在写这篇文章时发现的那些缺乏本地化灵活性/能力,有些缺乏动画支持......那么,该怎么办?从日期选择器代码中滚动您的“自己的”!这为您提供了一个功能齐全的月份选择器,具有日期选择器的所有功能,只是不显示日期。
我提供了一个monthpicker js-script和随附的CSS-script,使用下面描述的方法,以及jQuery-UI v1.11.1 代码。只需将这些代码片段复制到两个新文件,分别是monthpicker.js 和monthpicker.css。
如果您想了解我将 datepicker 转换为 monthpicker 的相当简单的过程,请向下滚动到最后一部分。然后,您也许可以使用更新版本的 jQuery-UI 重复该过程。
现在将日期选择器和月份选择器添加到页面!
这些以下 javascript 代码片段可与页面上的多个日期选择器和/或月份选择器一起使用,而不会出现上述问题!通常通过使用“$(this)”来修复。很多 :)
第一个脚本用于普通的日期选择器,第二个脚本用于“新”月份选择器。
注释掉的.after可以让您创建一些元素来清除输入字段,它是从 Paul Richards 的回答中窃取的。
我在我的月份选择器中使用“MM yy”格式,在我的日期选择器中使用“yy-mm-dd”格式,但这与所有格式完全兼容,因此您可以随意使用任何您想要的格式。只需更改“dateFormat”选项。标准选项“showButtonPanel”、“showAnim”和“yearRange”当然是可选的,可以根据您的意愿进行定制。
添加日期选择器
日期选择器实例化。 这是从 90 年前到现在的。它可以帮助您保持输入字段的正确性,特别是如果您设置了 defaultDate、minDate 和 maxDate 选项,但如果您不这样做,它也可以处理。它适用于您选择的任何 dateFormat。
注意:许多“新日期()”调用看起来很荒谬,但我找不到另一种方法将动态日期打包到声明中,而不为每个部分都这样做,因为我(据我所知)无法创建可重用的实例在这种情况下。如果有人知道在设置 minDate 和 maxDate 这样的上下文中设置增强日期的更好方法,我将不胜感激!
$('#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('');
// })
//)
;
添加月份选择器
在您要使用月份选择器的页面中包含monthpicker.js 文件和monthpicker.css 文件。
Monthpicker 实例化 从此monthpicker 检索的值始终是所选月份的第一天。从当月开始,范围从 100 年前到未来 10 年。
$('#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('');
// })
//)
;
就是这样! 这就是制作月份选择器所需的全部内容。
我似乎无法使 jsfiddle 使用它,但它在我的 ASP.NET MVC 项目中为我工作。只需像往常一样向页面添加日期选择器,并合并上述脚本,可能通过将选择器(意思是 $("#MyMonthTextBox"))更改为适合您的东西。
我希望这可以帮助别人。
一些额外的日期和月份选择器设置的粘贴箱链接:
Monthpicker 在该月的最后一天工作。您从这个月份选择器获得的日期将始终是该月的最后一天。
两个合作的月份选择器;“开始”在本月的第一天工作,“结束”在本月的最后一天工作。它们都相互限制,因此在“开始”所选月份之前的“结束”选择月份,会将“开始”更改为与“结束”相同的月份。反之亦然。可选:在“开始”选择月份时,“结束”上的“minDate”设置为该月份。要删除此功能,请在 onClose 中注释掉一行(阅读注释)。
两个协作的日期选择器;它们都受到彼此的限制,因此选择“结束”上的日期在“开始”所选日期之前,将“开始”更改为与“结束”相同的月份。反之亦然。可选:在“开始”上选择日期时,“结束”上的“minDate”设置为该日期。要删除此功能,请在 onClose 中注释掉一行(阅读注释)。
我如何将 DatePicker 更改为 MonthPicker
我已经从 jquery-ui-1.11.1.js 中获取了与他们的 datepicker 相关的所有 javascript 代码,将其粘贴到一个新的 js 文件中,并替换了以下字符串:
- “日期选择器” ==> “月份选择器”
- “日期选择器”==>“月份选择器”
- “日期选择器” ==> “月份选择器”
- “日期选择器” ==> “月份选择器”
然后我删除了创建整个 ui-datepicker-calendar div 的 for 循环部分(其他解决方案使用 CSS 隐藏的 div)。这可以在 _generateHTML: 函数 (inst) 中找到。
找到写着:
"</div><table class='ui-datepicker-calendar'><thead>" +
标记从结束 div-tag之后到(但不包括)它说的行的所有内容:
drawMonth++;
现在它会不高兴,因为我们需要关闭一些东西。在之前的关闭 div-tag 之后,添加以下内容:
";
代码现在应该很好地缝合在一起。这是一个代码片段,显示了您应该得到的结果:
...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 文件中,并替换了以下字符串:
- “日期选择器” ==> “月份选择器”
添加一个更简单的解决方案
$(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/
特点:
- 仅显示月/年
- 仅在单击完成按钮时将月份年份值添加到输入框
- 单击“完成”时没有“重新打开”行为
------------------------------------
另一个有效的解决方案很好的日期选择器和月份选择器在同一页面中:(也避免了在IE中多次单击上一个按钮,如果我们使用焦点功能可能会出现的错误)
JS小提琴链接
I needed a Month/Year picker for two fields (From & To) and when one was chosen the Max/Min was set on the other one...a la picking airline ticket dates. 我在设置最大值和最小值时遇到问题……另一个字段的日期将被删除。感谢上面的几个帖子......我终于想通了。您必须以非常特定的顺序设置选项和日期。
请参阅此小提琴以获取完整解决方案:月/年选择器 @ 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)
});
});
这被证明是有效的,但面临许多错误,所以我被迫在 datepicker 的几个地方打补丁:
if($.datepicker._get(inst, "dateFormat") === "mm/yy")
{
$(".ui-datepicker-calendar").hide();
}
patch1:在 _showDatepicker 中:平滑隐藏;
patch2: in _checkOffset: 修正月份选择器定位(否则当字段在浏览器底部时,偏移检查关闭);
patch3:在 _hideDatepicker 的 onClose 中:否则关闭日期字段时会闪烁很短的时间,这很烦人。
我知道我的修复远非好,但现在它正在工作。希望能帮助到你。
只是我还是这在 IE(8) 中不能正常工作?单击完成时日期会更改,但日期选择器会再次打开,直到您实际单击页面中的某个位置以放松对输入字段的关注...
我正在寻找解决这个问题。
<!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>
如果您正在寻找月份选择器,请尝试此jquery.mtz.monthpicker
这对我很有效。
options = {
pattern: 'yyyy-mm', // Default is 'mm/yyyy' and separator char is not mandatory
selectedYear: 2010,
startYear: 2008,
finalYear: 2012,
monthNames: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
};
$('#custom_widget').monthpicker(options);
我对接受的答案有一定的困难,并且没有其他答案可以以最小的努力作为基础。因此,我决定调整已接受答案的最新版本,直到它至少满足最低 JS 编码/可重用性标准。
这是一种比Ben Koehler接受的答案的第三版(最新版)更清洁的解决方案。此外,它将:
- 不仅适用于
mm/yy
格式,还适用于任何其他格式,包括 OP 的MM yy
. - 不要隐藏页面上其他日期选择器的日历。
datestr
不要用,month
等year
变量隐式污染全局 JS 对象。
看看这个:
$('.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');
}
});
您需要的其他一切都是以下CSS:
.datepicker-month-year .ui-datepicker-calendar {
display: none;
}
就是这样。希望以上内容能为更多读者节省一些时间。
在为 datepicker 挖掘 jQueryUI.com 之后,这是我的结论和对您问题的回答。
首先,我会对你的问题说不。您不能仅使用 jQueryUI 日期选择器来选择月份和年份。不支持。它没有回调函数。
但是您可以通过使用 css 隐藏日期等来破解它以仅显示月份和年份。而且我认为仍然没有意义,因为您需要单击日期才能选择日期。
我可以说你只需要使用另一个日期选择器。就像罗杰建议的那样。
如果有人也想要多个日历,那么将这个功能添加到 jquery ui 并不难。缩小搜索:
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';}
搜索
<table class="ui-datepicker-calendar
并将其替换为
<table class="ui-datepicker-calendar'+accl+'
也搜索
this._defaults={
将其替换为
this._defaults={justMonth:false,
对于 CSS,您应该使用:
.ui-datepicker table.ui-datepicker-just_month{
display: none;
}
之后,只需转到您想要的 datepicker init 函数并提供设置 var
$('#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
是这里的关键:)
我遇到了日期选择器与月份选择器混合的问题。我就这样解决了。
$('.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();
}
});
关于: http: //www.mattkruse.com/javascript/calendarpopup/
选择月份选择示例
对上面 BrianS 近乎完美的回应进行了一些改进:
我已经对显示的值设置了正则表达式,因为我认为在这种情况下它实际上确实使它更具可读性(尽管注意我使用的格式略有不同)
我的客户不想要日历,所以我添加了一个显示/隐藏类添加来做到这一点,而不会影响任何其他日期选择器。类的删除是在一个计时器上,以避免表格在日期选择器淡出时闪回,这在 IE 中似乎非常明显。
编辑:剩下要解决的一个问题是无法清空日期选择器 - 清除该字段并单击离开,它会重新填充所选日期。
EDIT2:我没有设法很好地解决这个问题(即没有在输入旁边添加一个单独的清除按钮),所以最终只使用了这个:https ://github.com/thebrowser/jquery.ui.monthpicker - 如果有人可以得到一个标准的 UI 来做这将是惊人的。
$('.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
}
我喜欢@user1857829 的回答和他的“extend-jquery-like-a-plugin 方法”。我只是做了一点修改,以便当您以任何方式更改月份或年份时,选择器实际上会在字段中写入日期。我发现在使用它之后我会喜欢这种行为。
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);
}
标记答案工作!但在我的情况下,日期选择器不止一个,只想在特定的日期选择器上实现
所以我使用 dp 的实例并找到 datepicker Div 并添加隐藏类
这是代码
<style>
.hide-day-calender .ui-datepicker-calendar{
display:none;
}
</style>
<script>
$('#dpMonthYear').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function (dateText, inst) {
$(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
},
beforeShow: function (elem,dp) {
$(dp.dpDiv).addClass('hide-day-calender'); //here a change
}
});
</script>
注意:您不能定位
.ui-datepicker-calendar
和设置 css,因为它会在选择/更改时不断渲染
我知道这有点晚了,但几天前我也遇到了同样的问题,我提供了一个很好且顺利的解决方案。首先我在这里找到了这个很棒的日期选择器
然后我刚刚更新了示例附带的 CSS 类 (jquery.calendarPicker.css),如下所示:
.calMonth {
/*border-bottom: 1px dashed #666;
padding-bottom: 5px;
margin-bottom: 5px;*/
}
.calDay
{
display:none;
}
当您更改任何内容时,该插件会触发一个事件 DateChanged,因此您没有点击一天并不重要(它适合作为年份和月份选择器)
希望能帮助到你!
我还需要一个月份选择器。我做了一个简单的,标题上有年份,下面有 3 行 4 个月。看看:简单的 jQuery 月份选择器。
我尝试了这里提供的各种解决方案,如果你只是想要几个下拉菜单,它们工作得很好。
这里建议的最佳(外观等)“选择器”(https://github.com/thebrowser/jquery.ui.monthpicker)基本上是旧版本的 jquery-ui datepicker 的副本,并重写了 _generateHTML。但是,我发现它不再与当前的 jquery-ui (1.10.2) 配合得很好,并且还有其他问题(在 esc 上不关闭,在其他小部件打开时不关闭,具有硬编码样式)。
我没有尝试修复那个月份选择器,也没有使用最新的日期选择器重新尝试相同的过程,而是挂钩到现有日期选择器的相关部分。
这涉及覆盖:
- _generateHTML(构建月份选择器标记)
- parseDate (因为它不喜欢没有日组件时),
- _selectDay(因为 datepicker 使用 .html() 来获取日期值)
由于这个问题有点陈旧并且已经得到很好的回答,这里只有 _selectDay 覆盖来显示这是如何完成的:
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);
};
如前所述,这是一个老问题,但我发现它很有用,所以想用替代解决方案添加反馈。
这就是它的完成方式。截至 2021 年 12 月
$('.monthpicker').datepicker({
autoclose: true,
showButtonPanel: true,
viewMode: "months",
minViewMode: "months",
format: "M-yyyy"
})
如果您想保持当前月份被选中,请添加
$('.monthpicker').datepicker({
autoclose: true,
showButtonPanel: true,
viewMode: "months",
minViewMode: "months",
format: "M-yyyy"
}).datepicker('setDate', new Date());
对于月份选择器,使用 jQueryv1.7.2
我有以下 javascript 正在这样做
$l("[id$=txtDtPicker]").monthpicker({
showOn: "both",
buttonImage: "../../images/Calendar.png",
buttonImageOnly: true,
// Default is 'mm/yyyy' and separator char is not mandatory
pattern: 'yyyymm',
monthNames: [
'Jan',
'Fev',
'Mar',
'Abr',
'Mai',
'Jun',
'Jul',
'Ago',
'Set',
'Out',
'Nov',
'Dez'
]
});
感谢 Ben Koehler 的解决方案。
但是,我遇到了多个日期选择器实例的问题,其中一些需要日期选择。Ben Koehler 的解决方案(在编辑 3 中)有效,但在所有情况下都隐藏了日期选择。这是解决此问题的更新:
$('.date-picker').datepicker({
dateFormat: "mm/yy",
changeMonth: true,
changeYear: true,
showButtonPanel: true,
onClose: function(dateText, inst) {
if($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1) {
$(this).datepicker(
'setDate',
new Date(
$("#ui-datepicker-div .ui-datepicker-year :selected").val(),
$("#ui-datepicker-div .ui-datepicker-month :selected").val(),
1
)
).trigger('change');
$('.date-picker').focusout();
}
$("#ui-datepicker-div").removeClass("month_year_datepicker");
},
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));
$("#ui-datepicker-div").addClass("month_year_datepicker");
}
}
});
使用onSelect
回调并手动删除年份部分并手动设置字段中的文本