Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery event handler .on() not working

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)

like image 470
Gowri Avatar asked Dec 23 '11 10:12

Gowri


People also ask

How to attach event handler in jQuery?

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.

How to bind event listener in jQuery?

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.

Why click is not working in jQuery?

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.


1 Answers

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.

like image 85
lonesomeday Avatar answered Oct 03 '22 12:10

lonesomeday