macca1 macca1 - 1 year ago 53
Javascript Question

Test if element already has jQuery datepicker

I have a form with many input elements. Some are date fields with a jQuery UI datepicker alraedy attached:

$("#someElement").mask("9?9/99/9999").datepicker({showOn: 'button', buttonText:'Click here to show calendar', duration: 'fast', buttonImageOnly: true, buttonImage: /images/calicon.gif' });

Then I have a key command bound to this function:

function openCalendar() {
var selection = document.activeElement;

// { Need to test here if datepicker has already been initialized
// }

This works great for elements which already have the datepicker on them. However any other fields will throw a javascript error. I'm wondering the best way to test to see if datepicker has already been initialized on that field.

Answer Source

Wow can't believe I missed this one. Line 108 of ui.datepicker.js:

/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: 'hasDatepicker',

So I just need to test for hasClass('hasDatepicker'). This seems like the most straightforward way. Furthermore, this statement checks whether the datepicker is currently opened (for anyone who is interested):

if ($("#ui-datepicker-div").is(":visible") && $("#ui-datepicker-div").html() != "") {
    // datepicker is open. you need the second condition because it starts off as visible but empty