JQuery DatePicker ReadOnly

You can set the range allowed to some invalid range so the user can't select any date:

$("#datepicker").datepicker({minDate:-1,maxDate:-2}).attr('readonly','readonly');     

All of the listed solutions give a mediocre user experience or cause issues if you want to re-enable the datepicker with it's settings in-tact. I used a method similar to making a select read-only, which is to disable it but add a hidden field with the same name. Check it:

Usage:

$("#datepicker").readonlyDatepicker(true); //makes the datepicker readonly
$("#datepicker").readonlyDatepicker(false); //makes the datepicker editable again

jQuery function:

$.fn.readonlyDatepicker = function (makeReadonly) {
    $(this).each(function(){

        //find corresponding hidden field
        var name = $(this).attr('name');
        var $hidden = $('input[name="' + name + '"][type="hidden"]');

        //if it doesn't exist, create it
        if ($hidden.length === 0){
            $hidden = $('<input type="hidden" name="' + name + '"/>');
            $hidden.insertAfter($(this));
        }

        if (makeReadonly){
            $hidden.val($(this).val());
            $(this).unbind('change.readonly');
            $(this).attr('disabled', true);
        }
        else{
            $(this).bind('change.readonly', function(){
                $hidden.val($(this).val());
            });
            $(this).attr('disabled', false);
        }
    });
};

My final solution:

When my app loads I initialize the datepicker as such:

$('.selector').datepicker({ dateFormat: "mm/dd/yy" }); 

I then have a global toggle button that enables/disables the datepicker. To disable I do the following:

$('.selector').datepicker("option", "minDate", -1);
$('.selector').datepicker("option", "maxDate", -2); 

To enable I do the following:

$('.selector').datepicker("option", "minDate", null);
$('.selector').datepicker("option", "maxDate", null); 

Thanks everyone!


I set the following beforeShow event handler (in the options parameter) to achieve this functionality.

beforeShow: function(i) { if ($(i).attr('readonly')) { return false; } }