We're using jquery UI 1.8.23 at my workplace.
How can I capture the date clicked in datepicker, so I can format the current date into a datestamp and pass that value into a hidden form field?
Here's some code I've tried to get working:
$('.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 looking at my code I appreciate any help you guys can offer.
You don't need to do anything to format the date. The DatePicker
widget does it for you.
Just use the altField
and altFormat
properties:
$("#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/
$('#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);
}
});
jQuery Datepicker
gives the option of formatting date. So why don't you make use of that?
$('element').datepicker({ dateFormat: 'dd-mm-yy' });
Also you don't need of a separate method to capture the click event. You the default method onSelect
$('input').datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function (date) {
//defined your own method here
alert(date);
}
})
Check this JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With