'jQuery Widgets not working on tabs loaded by Ajax

I have an application that has many tabs, apart from the first tab - all others are loaded via Ajax.

The tab content all loads correctly. However if I have a jQuery widget in a (ajax loaded) tab, the widget does not work.

I attempted to use:

$(document).on('click', '#dateOfBirth', function() {
    $( '#dateOfBirth' ).datepicker();
});

But the datepicker does not display.

Confusingly (for me):

$(document).on('click', '#dateOfBirth', function() {
    alert('This works properly');
});

Works properly! The alert displays when the date field is "clicked". And of course if I have a simple page without the tabs / ajax content - the datepicker displays as expected when the date field is clicked.

I am using the jQuery 2.2.0 and jQuery UI 1.12.0 with the "redmond" theme / CSS.

The view html follows the following;

<div class = "emr-bodycontent">
  <div id="tabs">
    <ul>
      <li><a href="#tabs-1">Patient Details</a></li>
      <li><a href="@emr.controllers.pas.routes.CarerDetails.carerDetails()">Carers</a></li>
...
...

Here is the JS used for the TABS;

$( "#tabs" ).tabs({
    beforeLoad: function( event, ui ) {
        ui.jqXHR.fail(function() {
            ui.panel.html(
                "There seems to be an error retrieving the data you requested."
            );
        });
    }
});


Solution 1:[1]

Instead of using click use focus and datepicker will work . Assumes that the element id is valid and is an input

$(document).on('focus', '#dateOfBirth', function() {
    $( '#dateOfBirth' ).datepicker();
});

For any other plugins inside tabs you can use load callback of tabs ... see api docs

DEMO

Solution 2:[2]

I will suggest you to setup the datepicker() after Ajax content loaded, do not use click event. Because the initiate call of $('#dateOfBirth').datepicker() is to set up the datepicker, you may need to click again to trigger the calendar.

Or, you can try to manually trigger it right after set.

$(document).on('click', '#dateOfBirth', function() {
  $(this).datepicker();
  $(this).datepicker("show");
 });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Keiran Tai