To get through the three approaches, the first one does not work because you are set up in such a way that #datepicker is not yet defined. You can verify this by replacing it with alert($('#datepicker').length) and seeing that it is zero.
The second approach is two clicks, because the datapicker does not know about the first click, because it was created after the click occurred.
The third approach works because it makes the datepicker appear after the first click. This is great, but a bit wasteful, because after you set up datepicker, it has its own event listener that will make it appear when the click starts.
Returning to your first approach, it did not work because #datepicker did not exist yet. You can do this job by moving ('#datepicker').datepicker() to the point after the code in which it is created.
If this is not possible, you can make your function work only on the first press, using the third approach, but switching from on to one . This will ensure that the first click is your event listener, which creates and displays the date selection. After that, your event listener will be deleted, and only the built-in date picker will exist.
However, I really hate $(document).on('click', ... because it evaluates every time you click on the page. It captures the event at the document level and then compares each item in the target list with a selector. It slowly and really stacks up if you have a lot of them. If you have to use a delegated listener, you have to transfer it to the closest parent. For example, if #datepicker always appears in #form1 , you can do $('#form1').on('click', ... instead, and reduce your processing.
source share