44

When I make my datepicker read-only, I see that the user cannot type anything into the text box.

$("#datepicker").attr('readonly', 'readonly');

However, they can still change the value using the calendar. How can I hide the calendar so that users cannot change the date value?

I do not want to disable the datepicker since I need the value posted to the server upon form submit.

("#datepicker").datepicker('disable');

Hutch Moore
  • 124
  • 1
  • 12
Bob
  • 785
  • 1
  • 11
  • 18
  • 3
    You want to use the datepicker behavior, yet you don't want the user to be able to select a date, nor change the date. Why exactly are you not using a simple input field? – Aaron McIver Oct 18 '11 at 18:44
  • Use a `` if you don't want any user interaction – Clive Oct 18 '11 at 18:46
  • 4
    @Aaron - There is a global lock/unlock button at the top. If locked then do not allow user to modify data. If unlocked then allow modifications. – Bob Oct 18 '11 at 20:23
  • @Clive - I want user interaction when the form is not "locked". – Bob Oct 18 '11 at 20:23
  • @AaronMcIver: A read-only date picker is a good date visualizer, even moreso for date ranges. It seems much more trivial for a date picker to have a read-only option than to build a date (range) visualizer from scratch, especially if your project might have a use for both in different places and want them to match. – hippietrail Dec 18 '12 at 00:14
  • check out this answer here http://stackoverflow.com/a/27057395/4251431 – Basheer AL-MOMANI Sep 08 '16 at 15:03

15 Answers15

90

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

beforeShow: function(i) { if ($(i).attr('readonly')) { return false; } }
Code Commander
  • 16,771
  • 8
  • 64
  • 65
28

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');     
mhu
  • 17,720
  • 10
  • 62
  • 93
Eduardo Molteni
  • 38,786
  • 23
  • 141
  • 206
  • Since I already initialized my datepicker I used the setter to do as you suggested. Thanks! – Bob Oct 20 '11 at 15:00
  • 1
    This is a nice quick and easy work-around for simple situations, but it's not ideal in all scenarios. For one, the datepicker still shows when clicked, which isn't a huge deal really. More importantly, you the lose state of the datepicker. If you're setting properties of the datepicker after it's instantiated, their values will all be lost when you re-instantiate it here. – Josh Noe Feb 01 '13 at 19:50
7

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);
        }
    });
};
Josh Noe
  • 2,664
  • 2
  • 35
  • 37
6

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!

Bob
  • 785
  • 1
  • 11
  • 18
  • 1
    FYI - how to modify multiple options at once: $(".selector").datepicker("option", { "minDate": -1, "maxDate": -2 }); – Bob Oct 20 '11 at 15:13
  • You can also do `$('.selector').datepicker("option", {minDate:-1,maxDate:-2})` to make it one-liner – Eduardo Molteni Oct 20 '11 at 15:16
5

I solved this with selector. I do not initialize the datetime picker on inputs which are readonly.

$('[type=datetime]:not([readonly])').datetimepicker();
gtu
  • 707
  • 1
  • 10
  • 22
4

If you're trying to disable the field (without actually disabling it), try setting the onfocus event to this.blur();. This way, whenever the field gets focus, it automatically loses it.

WWW
  • 9,734
  • 1
  • 29
  • 33
2

Sorry, but Eduardos solution did not work for me. At the end, I realized that disabled datepicker is just a read-only textbox. So you should make it read only and destroy the datepicker. Field will be sent to server upon submit.

Here is a bit generalized code that takes multiple textboxes and makes them read only. It will strip off the datepickers as well.

fields.attr("readonly", "readonly");
fields.each(function(idx, fld) {
    if($(fld).hasClass('hasDatepicker'))
    {
        $(fld).datepicker("destroy");
    }
});
OzrenTkalcecKrznaric
  • 5,535
  • 4
  • 34
  • 57
1

onkeypress = > preventdefault ...

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • This didn't work. The calendar image still pops up when clicking on the input box. – Bob Oct 20 '11 at 14:28
  • Actually it does work. I had to modify the options via the setter instead of trying to re-initialize. – Bob Oct 20 '11 at 14:59
  • 1
    because I can only select one answer right? Since I didn't actually use your code I didn't select this as the answer. I used Eduardo Molteni's answer above so I selected his. – Bob Nov 10 '11 at 21:02
0

I came up with another solution that is different than what had been proposed. When the date picker is used, it creates a div similar to a pop-up that is positioned when the input field is clicked on. To remove it, I just set the visibility property of the CSS so that it doesn't show up.

if ($('.yourDatepickerSelector').prop('readonly')) {
    $('#ui-datepicker-div').css({ 'visibility': 'hidden' })
} else { $('#ui-datepicker-div').css({ 'visibility': 'visible' }) }

This also seems to post correctly to the server, and should not effect any of the settings associated with it.

BBQ Singular
  • 457
  • 4
  • 15
0
<sj:datepicker id="datepickerid" name="datepickername" displayFormat="%{formatDateJsp}" readonly="true"/>

Works for me.

psousa
  • 6,676
  • 1
  • 32
  • 44
Bhimbim
  • 1,348
  • 2
  • 19
  • 15
0
      beforeShow: function(el) {
            if ( el.getAttribute("readonly") !== null ) {
                if ( (el.value == null) || (el.value == '') ) {
                    $(el).datepicker( "option", "minDate", +1 );
                    $(el).datepicker( "option", "maxDate", -1 );
                } else {
                    $(el).datepicker( "option", "minDate", el.value );
                    $(el).datepicker( "option", "maxDate", el.value );
                }
            }
        },
mauro
  • 1
0

During initialization you have to set to false the option enableOnReadonly which by default is true.

$('#datepicker').datepicker({
    enableOnReadonly: false
});

Then, you need to make the field readonly

$('#datepicker').prop('readonly', true);

See https://bootstrap-datepicker.readthedocs.io/en/latest/options.html#enableonreadonly

Junior
  • 313
  • 5
  • 12
0

by making date picker input disabled achieve this but if you want to submit form data then its a problem.

so after lot of juggling this seems to me a perfect solution

1.make your HTML input readonly on some condition.

<input class="form-control date-picker" size="16" data-date-format="dd/mm/yyyy"
                       th:autocomplete="off"
                       th:name="birthDate" th:id="birthDate"
                       type="text" placeholder="dd/mm/jjjj"
                       th:value="*{#dates.format(birthDate,'dd/MM/yyyy')}"
                       th:readonly="${client?.isDisableForAoicStatus()}"/>

2. in your js in ready function check for readonly attribute.

 $(document).ready(function (e) {

            if( $(".date-picker").attr('readonly') == 'readonly') {
                $("#birthDate").removeClass('date-picker');
            }
     });

this will stop the calendar pop up invoking when you click on the readonly field.also this will not make any problem in submit data. But if you make the field disable this will not allow you to submit value.

TanvirChowdhury
  • 2,498
  • 23
  • 28
0

This Worked For Me

document.getElementById("datepicker").disabled = true; //makes the datepicker readonly

document.getElementById("datepicker").disabled = false; //makes the datepicker enabled
Amar Kumar
  • 2,392
  • 2
  • 25
  • 33
-1
Readonly datepicker with example (jquery) - 
In following example you can not open calendar popup.
Check following code see normal and readonly datepicker.

Html Code- 

<!doctype html>
<html lang = "en">
   <head>
      <meta charset = "utf-8">
      <title>jQuery UI Datepicker functionality</title>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

      <!-- Javascript -->
      <script>
         $(function() {
                var currentDate=new Date();
                $( "#datepicker-12" ).datepicker({
                  setDate:currentDate,
                  beforeShow: function(i) { 
                      if ($(i).attr('readonly')) { return false; } 
                   }
                });
                $( "#datepicker-12" ).datepicker("setDate", currentDate);
                $("#datepicker-13").datepicker();
                $( "#datepicker-13" ).datepicker("setDate", currentDate);
        });
      </script>
   </head>

   <body>
      <!-- HTML --> 
      <p>Readonly DatePicker: <input type = "text" id = "datepicker-12" readonly="readonly"></p>
      <p>Normal DatePicker: <input type = "text" id = "datepicker-13"></p>
   </body>
</html>