[jquery] JQuery DatePicker ReadOnly

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');

This question is related to jquery datepicker

The answer is


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 solved this with selector. I do not initialize the datetime picker on inputs which are readonly.

$('[type=datetime]:not([readonly])').datetimepicker();

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.


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.


      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 );
                }
            }
        },

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');     

<sj:datepicker id="datepickerid" name="datepickername" displayFormat="%{formatDateJsp}" readonly="true"/>

Works for me.


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);
        }
    });
};

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


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.


onkeypress = > preventdefault ...


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");
    }
});

Readonly datepicker with example (jquery) - 
In following example you can not open calendar popup.
Check following code see normal and readonly datepicker.

Html Code- 

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang = "en">_x000D_
   <head>_x000D_
      <meta charset = "utf-8">_x000D_
      <title>jQuery UI Datepicker functionality</title>_x000D_
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"_x000D_
         rel = "stylesheet">_x000D_
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>_x000D_
_x000D_
      <!-- Javascript -->_x000D_
      <script>_x000D_
         $(function() {_x000D_
                var currentDate=new Date();_x000D_
                $( "#datepicker-12" ).datepicker({_x000D_
                  setDate:currentDate,_x000D_
                  beforeShow: function(i) { _x000D_
                      if ($(i).attr('readonly')) { return false; } _x000D_
                   }_x000D_
                });_x000D_
                $( "#datepicker-12" ).datepicker("setDate", currentDate);_x000D_
                $("#datepicker-13").datepicker();_x000D_
                $( "#datepicker-13" ).datepicker("setDate", currentDate);_x000D_
        });_x000D_
      </script>_x000D_
   </head>_x000D_
_x000D_
   <body>_x000D_
      <!-- HTML --> _x000D_
      <p>Readonly DatePicker: <input type = "text" id = "datepicker-12" readonly="readonly"></p>_x000D_
      <p>Normal DatePicker: <input type = "text" id = "datepicker-13"></p>_x000D_
   </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_