JQuery UI datepicker - attempt to capture click event from date pressed

We are using jquery UI 1.8.23 in my workplace.

How can I capture the date clicked in datepicker so that I can format the current date in datestamp and pass that value to a hidden form field?

Here is the code I tried to get:

$('.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); }); 

Thanks for watching my code. I appreciate any help you guys can offer.

+7
jquery jquery-ui datepicker
source share
4 answers

You do not need to do anything to format the date. The DatePicker widget does this for you. Just use the altField and altFormat :

 $("#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'); } }); 

Documentation:

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

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

Demonstration:

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

+12
source share

jQuery Datepicker provides the ability to format dates. So why don't you take advantage of this?

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

Also, you do not need a separate method to capture the click event. You use the default onSelect

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

Check JSFiddle

+1
source share
 $('#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); } }); 
+1
source share

Your receiver listens for this.

see function onSelect ()

Called when a date picker is selected. The function receives the selected date as text and an instance of datepicker as parameters. this refers to the corresponding input field.

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

All Articles