Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Datepicker - close on input click

I am using jQuery Datepicker and I have a little problem.

If the datepicker is opened, and you click on the input field again, nothing happens. How can I change that.. the picker to be closed on input click if it is already opened ?

Thanks in advance...

like image 810
Filip Avatar asked Sep 11 '10 11:09

Filip


4 Answers

I found a better way. hide seems to cause it not to open on further clicks. And blur causes the date picker to open a second later.

I used toggle:

$('.datepicker').mousedown(function() {
   $('#ui-datepicker-div').toggle();
});
like image 126
mbdev Avatar answered Nov 17 '22 11:11

mbdev


Since it's bound to focus (by default), you can just bind your own .mousedown() handler and it won't interfere, like this:

$("#datepicker").datepicker();
$("#datepicker").mousedown(function() {
    $(this).datepicker("hide");    
});

You can give it a try here. I'm using mousedown because that's how it's close behavior is detected as well, so just being consistent to more future-proof this behavior.

like image 29
Nick Craver Avatar answered Nov 17 '22 12:11

Nick Craver


Since I can't comment yet...

One annoying thing is since the datepicker uses focus, once you hide it, you can't show it again without blurring first and then focusing (so click somewhere else, then click in again).

I solved this by adding the following to Nick Craver's answer (inside the mousedown):

$(this).blur();

So it should look like this:

$("#datepicker").datepicker();
$("#datepicker").mousedown(function() {
    $(this).datepicker("hide");
    $(this).blur();
});
like image 2
davertron Avatar answered Nov 17 '22 10:11

davertron


This works for me (console.log method is output for testing – remove for production):

// call addToggleListener function one time to init
addToggleListener( $('.myDatepickerInputs') );

// the function
function addToggleListener( elm )
{
    elm.off( 'mouseup' );

    elm.on( 'mouseup', function()
    {
        $(this).off( 'mouseup' );
        $(this).datepicker( "show" );

        console.log( "show" );

        $(this).on( 'mouseup', function()
        {
            $(this).off( 'mouseup' );
            $(this).datepicker( "hide" );
            addToggleListener( $(this) );

            console.log( "hide" );
        });
    });
}

Calling the function using the datepickers „onClose“ option:

onClose: function()
{
    addToggleListener( $(this) );
}

Tested with Google Chrome.

like image 1
peterblunt Avatar answered Nov 17 '22 12:11

peterblunt