Reputation: 1053
I'm using this datepicker with an MVC3 application.
I want to have the input field as readonly
until an edit button is clicked. When the field is then in focus I want to call the datepicker.
The following code works fine if the page loads with the input editable. However, when I add the readonly attribute, the datepicker doesn't appear once the edit button is clicked and the field is no longer readonly. What is stopping the datepicker from being called?
$("[id$='Date']:not([readonly])").datepicker({ format: "dd MM yyyy" })
.focus(function () {
$(this).on('changeDate', function () {
$(this).datepicker('hide');
})
});
The code for changing the field from readonly to editable is as follows:
//enable editing and change button to "Update"
$("[id$='-edit']").click(function (e) {
var myButton = e.target.id;
//get text based on browser
var txt = e.target.textContent || e.target.innerText;
if (txt == 'Edit') {
e.preventDefault();
var myText = myButton.slice(0, (myButton.indexOf('-')));
$('#' + myText).prop('readonly', false);
e.target.textContent = 'Update';
//added below for browser compatibility
e.target.innerText = 'Update';
}
else {
window.onbeforeunload = null;
}
});
Razor and HTML generated by MVC:
Editable:
@Html.TextBoxFor(m => m.reviewDate)
<input data-val="true" data-val-required="The Review Date field is required." id="reviewDate" name="reviewDate" type="text" value="12 December 2013" class="valid">
Readonly:
@Html.TextBoxFor(m => m.reviewDate, new { @readonly = "readonly" })
<input data-val="true" data-val-required="The Review Date field is required." id="reviewDate" name="reviewDate" readonly="readonly" type="text" value="12 December 2013" class="valid">
The above readonly after the readonly attribute removed via the edit button code:
<input data-val="true" data-val-required="The Review Date field is required." id="reviewDate" name="reviewDate" type="text" value="12 December 2013" class="valid">
As per the accepted answer, I've changed the edit button code to assign the datepicker when the readonly attribute is removed.
This line...
$('#' + myText).prop('readonly', false);
...is now this:
$('#' + myText).prop('readonly', false).datepicker({ format: "dd MM yyyy" });
Upvotes: 0
Views: 970
Reputation:
This
$("[id$='Date']:not([readonly])").datepicker(...
does not assign the datepicker to elements that are readonly. If you change an element to remove the readonly attribute, you must then also assign the datepicker at that point.
Upvotes: 1