Aan*_*anu 372 javascript jquery jquery-ui date jquery-ui-datepicker
我正在使用jQuery日期选择器在我的应用程序中显示日历.我想知道我是否可以用它来显示月份和年份(2010年5月)而不是日历?
Ben*_*ler 420
这是一个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>
Run Code Online (Sandbox Code Playgroud)
EDIT jsfiddle上面的例子:http: //jsfiddle.net/DBpJe/7755/
编辑2 仅在单击完成按钮时将月份年值添加到输入框.还允许删除输入框值,这在上面的字段http://jsfiddle.net/DBpJe/5103/中是不可能的
EDIT 3
根据rexwolf的解决方案更新了Better Solution.
http://jsfiddle.net/DBpJe/5106
Len*_*rri 81
这段代码对我来说完美无缺:
<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" />
Run Code Online (Sandbox Code Playgroud)
输出是:
Bri*_*anS 61
@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>
Run Code Online (Sandbox Code Playgroud)
use*_*829 17
以上答案非常好.我唯一的抱怨是,一旦设定值,你就无法清除它.我也更喜欢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);
}
Run Code Online (Sandbox Code Playgroud)
然后像这样调用:
$('input.monthYearPicker').monthYearPicker();
Run Code Online (Sandbox Code Playgroud)
小智 10
<style>
.ui-datepicker table{
display: none;
}
Run Code Online (Sandbox Code Playgroud)
<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));
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
这将解决问题=)但我想时间格式yyyy-mm
虽然只在FF4尝试过
今天我有同样的需求,并在github上找到了这个,与jQueryUI一起使用,并且在日历中有月份选择器代替日期
https://github.com/thebrowser/jquery.ui.monthpicker
这就是我想出来的.它隐藏日历而不需要额外的样式块,并添加一个清除按钮来处理单击输入后无法清除值的问题.同样适用于同一页面上的多个月拍者.
HTML:
<input type='text' class='monthpicker'>
Run Code Online (Sandbox Code Playgroud)
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('');
})
);
Run Code Online (Sandbox Code Playgroud)
像许多其他人一样,我在尝试执行此操作时遇到了许多问题,并且只有发布的解决方案的组合,以及最终使其完美的大黑客,为我提供了一个适用于所有日期格式和本地化的解决方案,就像普通日期选择器。
我尝试过的该线程中其他解决方案的问题:
我终于找到了解决所有这些问题的方法,即使是在原来的日期选择器中!
注意:您不需要使用以下monthpicker 脚本来修复普通jQuery datepickers 中的前四个问题。只需使用本文后面的Datepicker 实例化脚本即可。问题 5 和问题 6 仅与我尝试过的不同月份选择器解决方案有关。
问题 1-3 和 5 与如何在其内部代码中引用日期和月份选择器有关,确保它们不会干扰其他日期和月份选择器,以及选择器的一些手动更新。您可以在下面的实例化示例中看到这一点。通过向 datepicker 函数添加一些自定义代码来修复第四个问题(参见示例中的注释,尤其是关于 onClose)。
对于第六个也是最后一个问题,仅与datepickers 一起使用monthpickers 相关,我们只需要正确分离 datepickers 和 monthpickers 。
那么,为什么不获取为数不多的自定义 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 选项,但如果您不这样做,它可以处理它。它适用于您选择的任何日期格式。
$('#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('');
// })
//)
;
Run Code Online (Sandbox Code Playgroud)
在要使用月份选择器的页面中包含 monthpicker.js 文件和 monthpicker.css 文件。
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('');
// })
//)
;
Run Code Online (Sandbox Code Playgroud)
就是这样! 这就是制作月份选择器所需的全部内容。
我似乎无法让 jsfiddle 使用它,但它在我的 ASP.NET MVC 项目中对我有用。只需执行您通常所做的将日期选择器添加到您的页面,并合并上述脚本,可能通过将选择器(意思是 $("#MyMonthTextBox"))更改为适合您的内容。
我希望这可以帮助别人。
Monthpicker 在本月的最后一天工作。您从此月选择器获得的日期将始终是该月的最后一天。
两个合作的月份选择器;“开始”在本月的第一天工作,“结束”在本月的最后一天工作。它们都相互限制,因此在“开始”所选月份之前选择“结束”月份,会将“开始”更改为与“结束”相同的月份。反之亦然。可选:在“开始”上选择月份时,“结束”上的“minDate”将设置为该月。要删除此功能,请在 onClose 中注释掉一行(阅读注释)。
两个协作日期选择器;它们都相互限制,因此在“开始”所选日期之前选择“结束”日期,会将“开始”更改为与“结束”相同的月份。反之亦然。可选:在“开始”上选择日期时,“结束”上的“minDate”将设置为该日期。要删除此功能,请在 onClose 中注释掉一行(阅读注释)。
我从 jquery-ui-1.11.1.js 中获取了与他们的日期选择器相关的所有 javascript 代码,将其粘贴到一个新的 js 文件中,并替换了以下字符串:
然后我删除了 for 循环的一部分,它创建了整个 ui-datepicker-calendar div(其他解决方案使用 CSS 隐藏的 div)。这可以在 _generateHTML: 函数 (inst) 中找到。
找到说:
"</div><table class='ui-datepicker-calendar'><thead>" +
Run Code Online (Sandbox Code Playgroud)
标记从关闭 div 标签之后到(不包括)它说的行的所有内容:
drawMonth++;
Run Code Online (Sandbox Code Playgroud)
现在它会不高兴,因为我们需要关闭一些东西。在关闭之前的 div-tag 之后,添加以下内容:
";
Run Code Online (Sandbox Code Playgroud)
代码现在应该很好地缝合在一起。这是一个代码片段,显示了您应该得到的结果:
...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...
Run Code Online (Sandbox Code Playgroud)
然后我将 jquery-ui.css 中与日期选择器相关的代码复制/粘贴到一个新的 CSS 文件中,并替换了以下字符串:
小智 5
我需要两个字段(From&To)的月/年选择器,当选择一个时,Max/Min设置在另一个...一个挑选的机票日期.我在设置max和min时遇到问题...其他字段的日期将被删除.感谢以上几篇帖子......我终于明白了.您必须按特定顺序设置选项和日期.
看完这个小提琴的完整解决方案:月/年选择器@ 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));
}
}
});
Run Code Online (Sandbox Code Playgroud)
如上所述,还将其添加到样式块:
.ui-datepicker-calendar { display: none !important; }
Run Code Online (Sandbox Code Playgroud)
小智 5
我结合了以上许多好的答案并得出了这个:
$('#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)
});
});
Run Code Online (Sandbox Code Playgroud)
这被证明有效,但面临许多错误,所以我被迫在几个datepicker的地方修补:
if($.datepicker._get(inst, "dateFormat") === "mm/yy")
{
$(".ui-datepicker-calendar").hide();
}
Run Code Online (Sandbox Code Playgroud)
patch1:在_showDatepicker中:平滑隐藏;
patch2:在_checkOffset中:纠正月份选择器定位(否则当该字段位于浏览器底部时,偏移检查关闭);
patch3:在_hideDatepicker的onClose中:否则当关闭日期字段时会闪烁很短的时间,这非常烦人.
我知道我的解决方案远非好,但现在它正在发挥作用.希望能帮助到你.
添加另一种简单的解决方案
$(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));
});
});
});
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/tmnasim/JLydp/
功能:
我对接受的答案有一定的困难,并且没有其他答案可以用最小的努力作为基础。因此,我决定调整已接受答案的最新版本,直到它至少满足最低 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');
}
});
Run Code Online (Sandbox Code Playgroud)
你所需要的其他一切就是下面的 CSS:
.datepicker-month-year .ui-datepicker-calendar {
display: none;
}
Run Code Online (Sandbox Code Playgroud)
就是这样。希望以上内容能为更多读者节省一些时间。
| 归档时间: |
|
| 查看次数: |
532089 次 |
| 最近记录: |