I want to attach a event to dynamically created element class.So i used live function but it was not triggered. So checked live function reference ,there i red below notes
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
so decide to use on function,But it still not working.The text field is already attached with jquery ui datpicker.On another element select i disabled that field.
jQuery("#from").attr('disabled','disabled') .removeClass('date_picker_bg') .removeClass('hasDatepicker') .addClass('date_picker_disabled');
after disabled if i click i want to show alert or tooltip.so i tried this,but not working
jQuery(".date_picker_disabled").on("click", function(event){ alert('hi'); });
What may be the problem
I am using jquery 1.7.1 ( jquery-1.7.1.min.js)
bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.
jQuery bind() MethodUse the on() method instead. The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.
So Why Does It Happen? JQuery OnClick Method is bound to an element or selector on page ready/load. Therefore if that element you want to click isn't there at the time of page ready, the binding can't happen.
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.
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