Questions

Jquery .click() function not working when element added dynamically.

0

I am using dynamic element using below code.

This function is being called from ajax request and adding the <li> element.

function select(data) {
  $(".tag-search").before('<li><a class="label label-info">'+data+'&nbsp;&nbsp;<span class="badge text-icon">×</span></a></li>');
}

and then, I am using click function on it using below code.

$(".text-icon").click(function(e){
  console.log('clicked');
});

But it is noty working.



asked 1 year, 10 months ago
Reputation: 1





1 Answer

0

jQuery .click() works great for most of the time, but we may encounter a problem when we add dynamic elements.

We can solve this problem using the code like below.

First find static tag in which that dynamic element exists and then use it like this. Here I am using .tag-conatiner

$(".tag-container").on('click', '.text-icon', function () {
   console.log("Clicked");
});

or else we can use body tag also.

$("body").on('click', '.text-icon', function () {
   console.log("Clicked");
});

answered 1 year, 10 months ago
Reputation: 1





Your Answer

Nothing to preview

Post Answer



Asked:  1 year, 10 months ago
Viewed:  572 times
Active:  1 year, 10 months ago