Jquery datepicker - manual triggering

Ondrej picture Ondrej · Nov 12, 2011 · Viewed 29.6k times · Source

I'm using a jquery datepicker in one of my project and I need to trigger the datepicker by clicking on a hyperlink which is next to my input area.

Unfortunately I can't get this working for some reason.

I have an input area and the hyperlink I would like to trigger a calendar in the input area.

<input type="text" id="date" /><a href="#" class="trigger">Show calendar</a>

I've tried to come up with a Javascript code such as:

$(".trigger").click(function(){ 
$("#date").datepicker("show"); 
}); 

As someone else in one of previous discussion suggested to use a SHOW method to make the calendar pop up. But it doesn't work.

Code such as

$(function() {
$("#date").datepicker();
});

works fine, but just by clicking into an input area (not on triggering hyperlink).

Does anyone have any idea or suggestion how to get this working? Becouse as far as I know I'm not the only one chasing the solution.

Thank you very much! ;)

Answer

Robert Van Sant picture Robert Van Sant · Nov 12, 2011

Is your click() event function in the jQuery(document).ready() function?

Because jQuery will recursively assign the click event handler to each class that you defined when the page loads.

Otherwise, it won't do anything if it's sitting outside the document ready function, like so:

$(function() {
    $("#date").datepicker();
    $(".trigger").click(function(){
        $("#date").datepicker("show");
    }); 
});

also I'll assume you have jQuery loaded and the datepicker plugin loaded in the head of the HTML document :)