Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  160] [ 2]  / answers: 1 / hits: 8497  / 11 Years ago, tue, december 10, 2013, 12:00:00

I use the following jquery in my page.



var j = jQuery.noConflict();
j(document).ready(function(){
console.log(j(#label_19));
j(#label_19).on(click,function(){
alert(Clicked);
});
});


When document loads, the element (it's a checkbox) appears in the console. But when I click the checkbox, the alert is not thrown. But when I copy the same code (as below)



    j(#label_19).on(click,function(){
alert(Clicked);
});


in console panel and press run. Now when I click the checkbox, the alert is thrown. What could be the issue in this case?



Updated:



What I observe in console is:



Object[input#label_19.document_label attribute value = Check-In]


The HTML markup is



<input id=label_19 class=document_label type=checkbox value=Check-In name=label[19]>

More From » jquery

 Answers
21

The only explanation that fits the facts you've presented is that there is code running after your ready callback but before you click the element that replaces the element in question. Some kind of ajax callback or similar.



You'll need to look through your code to find the place where that's happening. Things to look for are any html calls on elements that contain the #label_19 element, or (if there's a mix of jQuery and non-jQuery code) assignments to innerHTML.



You can use event delegation to solve this, which may or may not be the best answer depending on what your code is doing. That looks like this:



var j = jQuery.noConflict();
j(document).ready(function(){
console.log(j(#label_19));
j(document).on(click, #label_19, function(){ // This is the changed line
alert(Clicked);
});
});


There, instead of hooking click on the actual element, we're hooking it on document but then asking jQuery to only tell us about clicks that pass through elements matching the selector we give it as they bubble. That way, the fact that something is destroying and recreating the #label_19 element doesn't matter, because we're not hooking a handler on that element. We're hooking the handler on document and checking, when the event occurs, if it passed through something that matches that selector.



But I wouldn't just blindly use event delegation, I'd find out what's really happening with that element.


[#49674] Monday, December 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
martina

Total Points: 101
Total Questions: 103
Total Answers: 111

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;