[SalesForce] Disable Show Date Picker dynamically

I am trying to disable the Date Picker dynamically using jquery but it doesn't seem to be able to disable it using the usual stuff. I know in the apex tags you can disable showDatePicker, but i want to disable it dynamically on a pageload depending on a value. Anyone been able to disable showDatePicker?

Best Answer

When showDatePicker is true the onfocus of the input field calls some JavaScript:

<input onfocus="DatePicker.pickDate(true, 'p:f:x', false);" ...>

and when it is false that is missing. (Bear in mind that this is not part of Salesforce's published API so may change in future.)

So jQuery can be used to remove the onfocus handler when the page loads, and that logic can depend on client-side logic (which I presume is what you are looking for as server-side logic could just use the showDatePicker attribute). Here is an example page that has 2 date fields with the picker and 2 without:

<apex:page standardController="Contact">
    <apex:form>
        <apex:inputField value="{!Contact.Birthdate}" styleClass="noDatePicker"/>
        <apex:inputField value="{!Contact.Birthdate}"/>
        <apex:inputField value="{!Contact.Birthdate}" styleClass="noDatePicker"/>
        <apex:inputField value="{!Contact.Birthdate}"/>
    </apex:form>
<apex:includeScript value="{!URLFOR($Resource.Jquery)}"/>
<script>
var j$ = jQuery.noConflict();
// JQuery code could add the noDatePicker class or otherwise make this logic conditional
j$(document).ready(function() {
    j$('input.noDatePicker').each(function() {
        // Clear the DOM element onfocus
        this.onfocus = null;
    });
});
</script>
</apex:page>