When I make my datepicker read-only, I see that the user cannot type anything into the text box.
$(\"#datepicker\").attr(\'readonly\', \'readonly\');
I solved this with selector. I do not initialize the datetime picker on inputs which are readonly.
$('[type=datetime]:not([readonly])').datetimepicker();
onkeypress = > preventdefault ...
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.
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
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!
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 );
}
}
},