Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI datepicker - Trying to capture click event from date clicked

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.

like image 871
James Pickering Avatar asked Sep 05 '13 15:09

James Pickering


3 Answers

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/

like image 179
melancia Avatar answered Nov 15 '22 19:11

melancia


$('#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);
        }
    });
like image 36
PSN-RaffyBoy81 Avatar answered Nov 15 '22 19:11

PSN-RaffyBoy81


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

like image 40
Praveen Avatar answered Nov 15 '22 18:11

Praveen