RoJG
RoJG

Reputation: 49

Selecting elements with .on after .append of AJAX data

After dynamically adding elements using .append in a .ajax() call, not all of the elements that should be registered are being recognized by my .on('click, '.order_notes', ... ) call.

When I run the code .on('click', '.order_notes', ...) only it registers with the 3/4 of my elements with the class 'order_notes', all of them at the bottom of the generated page. The first 1/4 of the elements that I should be able to click on, all of them at the top of my generated page, don't register. I think I'm running into a race condition. Can anyone offer some insight into what is happening or how I might work around this problem?

The function being called on document load:

function getOrders(){

$.ajax({                                      
  url: path+'/ajax/orders.php',          
  data: "",                        
  dataType: 'json',                   
  success: function(data){  

    $('#content').empty();

    var output = "";
    var currentDate = "";
    var keeper = 0;

    for (var i in data){

        var id = data[i]['id'];
        var tId = data[i]['transaction_id'];
        var shop = data[i]['store'];
        var type = data[i]['type'];
        var msg = data[i]['msg'];
        var timestamp = data[i]['timestamp'];

        var datetime = timestamp.split(" ");
        var date = datetime[0];
        var time = datetime[1];

       if(keeper == 0){
            output+="<div class=daily_order_record><b>" + date +"</b></br>";
            currentDate = date;
            keeper++;
        }

       if(currentDate != date && keeper != 0){
            output+="</div><div class=daily_order_record><b>" + date +"</b></br>";
            currentDate = date;
            keeper++;
        }

      output +="<p class=\"order_notes\" id=t_"+ tId +">" + time + "  " + shop + "  " + msg + "</p>"; 

  }

  $('#content').hide().append(output).fadeIn(500); 

  }

 });    
}

The code registering .on click handlers:

$(document).ready( function() {

  $(document).ajaxComplete(function() {
      $('html').on('click', '.order_notes', function(){

          alert("hi");
      });
  });

});

Additional Code that I have tried to register .on click handlers with the same result:

$(document).ready( function() {

  $('html').on('click', '.order_notes', function(){
      alert("hi");
  });

});

Upvotes: 0

Views: 61

Answers (1)

scrowler
scrowler

Reputation: 24405

Put your on event handler outside the ajaxComplete callback, but still inside the document.ready. The idea of on is that it will listen past the original DOM creation/ready point, including all elements loaded by AJAX after this point:

$(document).ready(function() {
    $('html').on('click', '.order_notes', function() {
        alert('hi');
    });
    $(document).ajaxComplete(function() {
        // whatever else you do in your callback
    });
});

Another thing to note is that you are currently assigning that click handler to .order_notes elements within the html element - this is a very large scope and bubbling will occur across many levels. You could do better to narrow down your target by using the #content div instead of html as a base so your event handler:

$('#content').on('click', '.order_notes', function() {});

Upvotes: 2

Related Questions