Search code examples
javascriptjqueryjquery-uikeypressjquery-ui-datepicker

jQuery datepicker change date on keypress without CTRL key pressed


I use a datepicker and documentation says we can change the date on keypress (es. CTRL+LEFT: Move to the previous day) .... but I would like change date in this case:

  • LEFT -> Move to the previous day
  • RIGHT-> Move to the next day
  • UPP-> Move to the previous week
  • DOWN -> Move to the next week

I've this code:

$(document).on('focus', '.datepicker',  function() {
    $(this).datepicker({ dateFormat: "dd-mm-yy" }).attr('readonly','readonly');
    if($(this).val()=='') $(this).val($.datepicker.formatDate('dd-mm-yy', new Date()));
    // how can I activate a crtl key??
});
$(document).on('focusout', '.datepicker',   function() {
    // how can I deactivate a crtl key??
});

If this isn't the way any suggestion is welcome

Thanks


Solution

  • Thank so much ... You have inspired me ... I solved by this code:

    $(document).on('focus', '.datepicker',  function() {
        $(this).datepicker({
            dateFormat: "dd-mm-yy"                  
        });
        if($(this).val()=='') $(this).val($.datepicker.formatDate('dd-mm-yy', new Date()));
    });
    
    $(document).on('keydown', '.datepicker',    function() {
        $.datepicker.customKeyPress(event);
    });
    
    $.extend($.datepicker, { // Extends datepicker with shortcuts.
        customKeyPress: function (event) {
            var inst = $.datepicker._getInst(event.target);
            var isRTL = inst.dpDiv.is(".ui-datepicker-rtl");
            switch (event.keyCode) {
                case 37:    // LEFT --> -1 day
                    $('body').css('overflow','hidden');
                $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
                break;
            case 38:    // UPP --> -7 day
                $('body').css('overflow','hidden');
                $.datepicker._adjustDate(event.target, -7, "D");
                break;
            case 39:    // RIGHT --> +1 day
                $('body').css('overflow','hidden');
                $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
                break;
            case 40:    // DOWN --> +7 day
                $('body').css('overflow','hidden');
                $.datepicker._adjustDate(event.target, +7, "D");
                break;
            }
            $('body').css('overflow','visible');
        }
    });
    

    I hope this code is useful

    Bye