-1

The first click event sends an API call that returns several search results.

The second click event should occur when clicks 'upvote', which is an option in each returned search result.

Problem is, it seems that I can't select upvote buttons in search results because they were created (via cloning another element) after the first click event.

Can anyone explain why this happens?

Part of the first click event:

success: function(json) {
  var reviews = json.reviews;

  $.each(reviews, function(i) {
    var critic = reviews[i].critic;
    var quote = reviews[i].quote;
    var score = reviews[i].original_score;

    $('#tile-demo').clone().removeAttr('id').removeClass('hidden')
    .find('.critic-name').text(critic).end()
    .find('.critic-score').text(score).end()
    .find('.critic-quote').text(quote).end()
    .appendTo('.review-grid');
  }); //end each loop

} //end success call

the new call, which should select a clone of #tile-demo:

$('.search-results').click(function(){
  var goodCritic = $(this).siblings('.critic-name').text();
  console.log(goodCritic);
});
elclanrs
  • 92,861
  • 21
  • 134
  • 171
Bryce Johnson
  • 6,689
  • 6
  • 40
  • 51

2 Answers2

1

Use On method as the following:

$('#containerId').on('click','upvotebuttons',function(){write your code here});

where containerId is the id of the container div where you render new data, and replace [upvotebuttons] with [class name] of the upvote buttons.

Shhade Slman
  • 263
  • 2
  • 10
0

I just came across a quick screencast by Jeffrey Way that suggests a slightly different solution. The other answer works fine--this is just another way to go about it (still uses event delegation).

$('#parent-of-target').click(function(e) {  

    if ( $(e.target).is('#target-element') ) {  
        alert('clicked');  
    }  
});  
Bryce Johnson
  • 6,689
  • 6
  • 40
  • 51