Test if element already has Bootstrap datepicker

mapto picture mapto · Apr 20, 2015 · Viewed 7.3k times · Source

I am working on a rather big software platform that has several implementations. There is one previous implementation that uses jQueryUI datepicker, and I am now working on an interface revamp that uses Bootstrap datepicker.

Is there a way for me to test whether a Bootstrap datepicker is already attached to a certain element, let's say this one

<input type="text" id="user-date" class="datepicker"/>

Notice that I am not asking whether Bootstrap datepicker is loaded as in this qestion. I'm rather asking for a test, similar to this one for jQueryUI datepicker.

Answer

Abraham Uribe picture Abraham Uribe · Apr 20, 2015

when you use bootstrap-datepicker on a element it adds a object in .data("datepicker") so you can just check if it exists and to check if the datepicker is visible you can use the .data("datepicker").picker object like this

HTML

<input type="text" id="user-date" class="datepicker"/>     

JS

if(!$('#user-date').data('datepicker')){// or $('#user-date').data('datepicker')==null
    console.log('datepicker is not attached');
}   
$('#user-date').datepicker();
$('#user-date').focus();//set focus to display datepicker
if($('#user-date').data('datepicker')){
    console.log('datepicker is already attached');
    if($('#user-date').data('datepicker').picker.is(":visible")){
        console.log("datepicker is visible");
    }
}

https://jsfiddle.net/weso8a96/