Creating a live datpicker - jQuery

I know when you create an element dynamically, you should use something like:

$("#id").live("click", function() { //something }); 

Now I have this:

 $('#tdInput1').datepicker({ inline: true }); 

My question is: how can I do this live so that it can interact with dynamically created elements.

+7
source share
4 answers

According to: Jquery.live works, but not with .datepicker

This should work:

 $("#tdInput1").live("click", function(){ $(this).datepicker({ inline: true }); }); 

edit: This answer is for older versions of jQuery. For jQuery 1.9+ try answering Vishal.

+11
source

The decision made will not work with keyboard focus events .. so I had to change to this:

 $('.parent').on('focusin', '.datepicker', function(e) { $(this).datepicker(options); }); 

I had to change .live to .on , since jquery 1.9.1 does not include the .live method. The above works for mouse events as well as keyboard events.

+19
source

You are dealing with two different things. jQuery live is for event binding, and datepicker not datepicker attached to the event, but simply adds functionality to the element at a time.

The only reason live works with events is because jQuery actually binds the event handler to the predecessor element and (thanks to the way the events bubble in javascript) the ancestor actually accepts the event and delegates it as if it were coming from the item. The principle is quite complex, but long and short, it can only work with events.

If you want to add the datepicker function, just call the datepicker function of the new element after it is created.

+7
source

I think a more correct solution:

 $('input.datepickerClass').live('focus', function(){ if (false == $(this).hasClass('hasDatepicker')) { $(this).datepicker({ options }); } }); 
0
source

All Articles