Jquery – Open JQuery Datepicker by clicking on an image w/ no input field

datepickerjquery

I want to have the JQuery Datepicker open when the user clicks on an image. There is no input field where the selected date appears afterwards; I'm just going to save the entered date to the server via Ajax.

Currently I have this code:

<img src='someimage.gif' id="datepicker" />

$(document).ready(function() {
    $("#datepicker").datepicker({
            changeMonth: true,
            changeYear: true,
        }).click(function() { $(this).datepicker('show'); });
 });

But nothing happens when I click on the image. I have also tried saving the result of the datepicker() call to a global var and then calling datepicker('show') from the onclick() event of the image, but same result.

Best Answer

Turns out that a simple hidden input field does the job:

<input type="hidden" id="dp" />

And then use the buttonImage attribute for your image, like normal:

    $("#dp").datepicker({
        buttonImage: '../images/icon_star.gif',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        showOn: 'both',
     });

Initially I tried a text input field and then set a display:none style on it, but that caused the calendar to emerge from the top of the browser, rather than from where the user clicked. But the hidden field works as desired.

JSFiddle

Related Topic