To make this post clear, by ReadOnly
I mean really read only, no input allowed whatsoever.
DatePicker Default Behavior
This one seemed easy at first but it isn't just because by design, setting the input textbox
to readonly
, the widget will understand it as if we just wanted to limit the user to choose a date from the popup, disallowing any input text.
What I want here is to block any way for the user to change the textbox
value, either from the calendar popup or by direct input on the textbox
.
Option 1: Disable Textbox
The good | The bad |
Works! | Grays out the control to make it look disabled |
This would be a quick solution by just disabling the textbox
but it kind of shades the control, and I want it to display its value with the same appearance as the other textbox
es. Not approved!
Option 2: Bend the Control
This DatePicker
widget has a lot of options, we just have to find a way to use them in our favor to achieve this "unsupported" behavior.
<input type="text" id="txtDate" readonly="readonly" />
<script type="text/javascript">
$(document).ready(function () {
$('#txtDate').datepicker(
{
beforeShow: function (input, inst)
{ inst.dpDiv = $('<div style="display: none;"></div>'); }
});
});
</script>
If you want to be able to toggle between editable and readonly modes, you'll need a couple more lines of code:
<input type="text" id="txtDate" readonly="readonly" />
<script type="text/javascript">
$(document).ready(function () {
$('#txtDate').datepicker(
{
beforeShow: function (input, inst)
{
if($(input).attr('readonly') !== undefined ) {
if(inst.o_dpDiv === undefined) {
inst.o_dpDiv = inst.dpDiv;
}
inst.dpDiv = $('<div style="display: none;"></div>');
} else {
if(inst.o_dpDiv !== undefined) {
inst.dpDiv = inst.o_dpDiv;
}
}
}
});
});
</script>
Here's a live demo, courtesy of commenter: http://jsfiddle.net/AlexCode/985teLaw/2/
What did I do?
On the textbox
, you can see that I made it read-only, but as I said, this alone still lets the user change the date from the calendar popup. To block the calendar popup, I'm replacing it with an empty DIV
element, and to avoid unhandled complications, I'm styling it as display: none
.
With this workaround, the DatePicker
still thinks it is showing the popup
but in fact nothing happens.
This is kind of tricky but is pretty easy to do and works very well on all browsers.
My Recommendation to the jQuery UI Team
This would be so much easier if we need only pass something like: showOn: "never"
.