jQuery event handler .on() not working
The problem is that jQuery(".date_picker_disabled")
finds elements with that class and binds to them. If elements don't have the class at the time the binding is made, the events will not be handled.
The on
function allows you to get round this by handling them on another element when the event "bubbles up to" a parent element. In this instance, we could say the body
element – there may be a more specific common parent you could choose.
jQuery(document.body).on('click', '.date_picker_disabled', function(event) { alert('hi');});
The event handler is now bound to the document.body
element. All clicks that happen anywhere in the body are tested to see if they originated from an element matching the selector. If so, the handler is fired.
This is explained on the documentation for the on
function. It is the same behaviour as was present in previous versions of jQuery with live
and delegate
functions.
Having taken another look at your code, you have disabled="disabled"
set on your input
element. click
events are not fired on disabled elements.
This is tricky.
When your code runs, your element does not have .date_picker_disabled
class so your jQuery(".date_picker_disabled")
returns nothing and .on()
is not called.
Apply .on() on the outer element and use the selector parameter:
// you can also do $(document).on()$(<outer element>).on('click', '.date_picker_disabled', function() { // do something});
This will delegate the event to the <outer element>
. The handler will only be executed if an element with class .date_picker_disabled
has been clicked (second param).
From the documentation of .live()
:
Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:
$(selector).live(events, data, handler); // jQuery 1.3+$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+ $(document).on(events, selector, data, handler); // jQuery 1.7+
So in your case, you would do:
$(document).on('click', '.date_picker_disabled', function(event){ alert('hi');});