gpt4 book ai didi

javascript - 用于月份和年份选择的 jQuery UI DatePicker 不起作用

转载 作者:行者123 更新时间:2023-11-29 18:09:05 28 4
gpt4 key购买 nike

我使用 jquery datepicker 作为 monthpicker 并且它正在工作,但唯一的问题是如果我从 calander 选择一个月然后它在输入字段中显示该月份,但是当我再次单击该输入字段时它不会显示所选月份,但它显示当前月份。

HTML

<label for="startDate">Date :</label>
<input name="startDate" id="startDate" class="date-picker" />

JS

$(function() {
$('.date-picker').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function(dateText, inst) {



function isDonePressed(){
return ($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1);
}

if (isDonePressed()){

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));
console.log('Done is pressed')

}



}
});
});

这是我的问题的 fiddle 。 http://jsfiddle.net/DBpJe/5103/

最佳答案

您必须像下面这样更改 beforeShow,而且由于月份名称在字符串中,您必须有一个这样的数组来将月份映射到数字

var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
beforeShow: function(input, inst) {
inst.dpDiv.addClass('month_year_datepicker')
if ((datestr = $(this).val()).length > 0) {
datestr = datestr.split(" ");
year = datestr[1];
month = monthNames.indexOf(datestr[0]);
$(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
$(this).datepicker('setDate', new Date(year, month, 1));
$(".ui-datepicker-calendar").hide();
}
}

这里是 demo 1

或者您可以使用这种更好看的方法将月份转换为数字

function getMonthFromString(mon){
return new Date(Date.parse(mon +" 1, 2012")).getMonth()+1
}

礼貌:SO answer

这里是 demo 2

关于javascript - 用于月份和年份选择的 jQuery UI DatePicker 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29098871/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com