i'm using asual jquery-address, tabs example and want to add datepicker to the "Extra" tab. If i'm just adding
$(document).ready(function() {
$( "#datepicker" ).datepicker();
});
it wont work. So i found out i have to use .live(). As im using jquery-1.7 .live() has changed to .on().
If i add this code datepicker only works on the second click.
$(document).ready(function() {
$(document).on('click', '#datepicker', function () {
$(this).datepicker();
});
});
I saw in another thread a not recommended way to make it work like this
$(document).ready(function() {
$(document).on('click', '#datepicker', function () {
$(this).datepicker().datepicker( "show" );
});
});
How am i using it correctly? Is there a recommended way to make datepicker work like i want in this example?
I think i need to use .on() because i want to reload the form that's including #datepicker with a .load() event.
To walk through your three approaches, the first one is failing because your is set up in a way such that #datepicker
is not yet defined. You could check this by replacing it with alert($('#datepicker').length)
and seeing that it is zero.
The second approach is taking two clicks because the datepicker is unaware of the first click because it was created after the click occured.
The third approach works because it forces the datepicker to appear after the first click. That is fine but a little wasteful because after you set up the datepicker, it has its own event listener that will make it appear when the click starts.
Going back to your first approach, it wasn't working because #datepicker
didn't exist yet. You could make this work by moving ('#datepicker').datepicker()
to after the point in the code where it is created.
If this is not possible, you can make it so your function only fires on the first click by using the third approach but switching from on
to one
. This will make it so the first click is your event listener that creates and shows the date picker. After that, your event listener will be removed and only the built-in date picker listener will exist.
That said, 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 every element in the target list to the selector. This is slow and really adds up if you have a lot of them. If you must use a delegated listener, you should move it to the closest parent. For example, if #datepicker
always appears in #form1
, you could do $('#form1').on('click', ...
instead and reduce your processing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With