jquery-uijquery-ui-widget-factory

Determining the type of a standard jQueryUI widget


I am having trouble determining the type of a given jQueryUI widget instance.

The jQueryUI documentation for the Widget Factory suggests two techniques. From the "Instance" section:

The widget's instance can be retrieved from a given element using the instance() method. [...] If the instance() method is called on an element that is not associated with the widget, undefined is returned.

the :data selector can also determine whether an element has a given widget bound to it.

Based on their examples, let's say I initialize a datepicker and later code checks if it is a datepicker:

<p>Date: <input type="text" id="datepicker"> </p>

  $(function() {
    $("#datepicker").datepicker();

    // ...
    var i = $("#datepicker").progressbar("instance"); // i is undefined as expected
    console.log(i);
    var b = $("#datepicker").is(":data('ui-datepicker')"); // b = false, not sure why
    console.log(b);
    var i2 = $("#datepicker").datepicker("instance"); // this throws an exception
    console.log(i2);
  });

Based on the documentation I expected the .is call to return true, and the last line to return the instance (not throw an exception.)

JSFiddle is here. (You will need to open the browser's console to see the logged output.)


Solution

  • It turns out the techniques I listed above do work for many jQueryUI widgets, e.g. button, progressbar.

    But datepicker is kind of weird. Looking at the DOM after a datepicker is initialized, I see the datepicker is inserted as a new element after the named element.

    To get the datepicker widget instance I'd need to navigate the DOM starting from the named element. To check if the input field has a datepicker on it we can simply check the element for the class hasDatepicker:

    var isDatePicker = $("#datepicker").is(".hasDatepicker");
    

    This works with jQueryUI 1.11.2, and based on other SO questions it's been working since 2009. So I guess it's a reliable technique, but I'm not sure if its documented anywhere, or guaranteed for future versions.