jQuery UI datepicker – 尝试从点击日期捕获点击事件

我们在我的工作场所使用jquery UI 1.8.23。

如何捕获datepicker中单击的日期,以便将当前日期格式化为日期戳并将该值传递给隐藏的表单字段?

这是我尝试过的一些代码:

$('.ui-state-default').live('click', function(){ console.log('date clicked'); var currentdate = $(this).text(); var d = currentdate; var m = monthFormat($('.ui-datepicker-month').text()); var y = $('.ui-datepicker-year').text(); $('a.ui-state-default').removeClass('ui-state-highlight'); $(this).addClass('ui-state-highlight'); if (currentdate.length < 2) { d = "0" + currentdate; } var datestamp = y + "-" + m + "-" + d; console.log(datestamp); $('#dateHidden').val(datestamp); }); 

感谢您查看我的代码,感谢您提供的任何帮助。

您无需执行任何操作来格式化日期。 DatePicker小部件为您完成。 只需使用altFieldaltFormat属性:

 $("#myDatePicker").datepicker({ // The hidden field to receive the date altField: "#dateHidden", // The format you want altFormat: "yy-mm-dd", // The format the user actually sees dateFormat: "dd/mm/yy", onSelect: function (date) { // Your CSS changes, just in case you still need them $('a.ui-state-default').removeClass('ui-state-highlight'); $(this).addClass('ui-state-highlight'); } }); 

文档:

http://api.jqueryui.com/datepicker/#option-altField

http://api.jqueryui.com/datepicker/#option-altFormat

示范:

http://jsfiddle.net/sFBn2/10/

jQuery Datepicker提供了格式化日期的选项。 那么你为什么不利用它呢?

 $('element').datepicker({ dateFormat: 'dd-mm-yy' }); 

此外,您不需要单独的方法来捕获click事件。 你是onSelect的默认方法

 $('input').datepicker({ dateFormat: 'yy-mm-dd', onSelect: function (date) { //defined your own method here alert(date); } }) 

检查这个JSFiddle

 $('#calendar').datepicker({ inline: true, firstDay: 1, changeMonth: false, changeYear: true, showOtherMonths: true, showMonthAfterYear: false, yearRange: "2015:2025", dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], dateFormat: "yy-mm-dd", onSelect: function (date) { alert(date); } }); 

你的datepicker听了。

请参阅onSelect()函数

选择日期选择器时调用。 该函数接收选定的日期作为文本,并将datepicker实例作为参数。 这指的是相关的输入字段。

 $('.date-pick').datepicker( { onSelect: function(date) { //play with date here }, ---- ---- ---