Naveen Kumar
Naveen Kumar

Reputation: 1616

on click not working as expected on dynamically created elements jQuery

I have a tag when clicked alerts the data-value of the tag. It works fine , but doesn't works when i click on dynamically created elements.

<img id="no_p_fav" src="http://localhost:8000/icons/non_star.png">

Below is how i create dynamic elements

 $('.all_candidate_bar').prepend('<div id = "icons"> <a class = "favorite" data-value = "'+data.msg.id+'" > <img id = "no_p_fav" src="{{url("/icons/non_star.png")}}" ></img></a></div>');

Below function doesn't work on dynamically created elements but works fine on elements which were there when the page was loaded.

$(document).ready(function(){

    $('.favorite').on('click',function(){
        var candidate_id = $(this).data('value');
        alert(candidate_id);
    }); 
});

I have also tried this

 $('#icons').on('click','a.favorite',function(){//myFunction});
 $('a').on('click','.favorite',function(){//myFunction});

How do i make it work for elements for both dynamic and static elements ?

Upvotes: 0

Views: 86

Answers (4)

Jishnu V S
Jishnu V S

Reputation: 8409

change your function like this way

$(function(){
   $(document).on('click','.favorite',function(){
      var candidate_id = $(this).data('value');
      alert(candidate_id);
});

Upvotes: 0

KAD
KAD

Reputation: 11102

Since the #icon is also created dynamically you cannot use event delegation against it, you need a higher level element that is there since the beginning, body for instance:

$('body').on('click','.favorite',function(){//myFunction});

The a also won't work, since the event is not delegated in this case, it is accessing the element itself

$('a').on('click','.favorite',function(){//myFunction}); // won't work

Upvotes: 3

brk
brk

Reputation: 50291

For dynamically created element you need to to delegate the event $(document).ready(function(){

    $('body').on('click','.favorite',function(){
        var candidate_id = $(this).data('value');
        alert(candidate_id);
    }); 
});

Upvotes: 0

vengatesh rkv
vengatesh rkv

Reputation: 327

Try this Code:

$(document).ready(function(){

    $(document).on('click','.favorite',function(){
        var candidate_id = $(this).data('value');
        alert(candidate_id);
    }); 
});

Upvotes: 0

Related Questions