I have content that is dynamically added into the index page via ajax calls with the history api (I use pushstate and onpopstate).
For a specific page that will be loaded I have a form with a date field like this:
<tr>
<td class='input-group date' id='datetimepicker1'>
<input style='width: 250px; border: 0; outline: none; name='invoicedate' value='2017-10-01' data-date-format='YYYY-MM-DD'>
<span class='input-group-addon'>
<span class='glyphicon glyphicon-calendar'></span>
</span>
</td>
</tr>
from the index page I want to attach a click event to datetimepicker1 so that the Bootstrap datetimepicker widget will show. I use this snippet:
$("#container").on("click", "#datetimepicker1", function(){
$("#datetimepicker1").datetimepicker({
locale: 'nl',
format: 'YYYY-MM-DD',
allowInputToggle: true,
useCurrent: false,
});
});
The problem is that I need to click twice on the datepicker before the widget shows up.
After doing that the datepicker shows up directly when clicked for the third time.
I have tried to wrap the above with $(document).ready(function () { } but that didnt work, because I think the added content with ajax calls via innerhtml doesn't fire a page reload. Also some people said to use delegated events which I do as you can see and it still doesn't work.
Anyone got thoughts on this why this happens? I also tried to inspect the code with Google Developer tools from the console pane: monitorEvents(window, "click") and $._data(($0), 'events') but it is too verbose and I don't know how to use the information for debugging like event bubbling.
Thanks for helping!
Your problem is that you're adding datepicker on click on #container - that's probably some div that wraps everything:
$("#container").on("click", "#datetimepicker1", function(){
$("#datetimepicker1").datetimepicker({
locale: 'nl',
format: 'YYYY-MM-DD',
allowInputToggle: true,
useCurrent: false,
});
});
So first time you click you're actually adding datepicker on your container, your code should look like this without any onclick event:
$("#datetimepicker1 input[name='invoicedate']").datetimepicker({
locale: 'nl',
format: 'YYYY-MM-DD',
allowInputToggle: true,
useCurrent: false,
});
You also need to wrap this up on element creation if this is done dynamically.