I am trying to record a click on an anchor that is created asynchronously.
An asynchronous call that works fine looks like this:
$("#txt_search").keyup(function() { var search = $("#txt_search").val(); if (search.length > 0) { $.ajax({ type: "post", url: "<?php echo site_url ('members/searchmember') ;?>", data:'search=' + search, success: function(msg){ $('#search_results').html(""); var obj = JSON.parse(msg); if (obj.length > 0) { try { var items=[]; $.each(obj, function(i,val){ items.push($('<li class="search_result" />').html( '<img src="<?php echo base_url(); ?>' + val.userImage + ' " /><a class="user_name" href="" rel="' + val.userId + '">' + val.userFirstName + ' ' + val.userLastName + ' (' + val.userEmail + ')</a>' ) ); }); $('#search_results').append.apply($('#search_results'), items); } catch(e) { alert(e); } } else { $('#search_results').html($('<li/>').text('This user does not have an account yet')); } }, error: function(){ alert('The connection is lost'); } }); } });
The anchor I want to get to is <a class="user_name" href="" rel="' + val.userId + '">' + val.userFirstName + ' ' + val.userLastName + ' (' + val.userEmail + ')</a>'
I detect a click on these anchors with this function:
// click op search results $("a.user_name").on('click', function(e) { e.preventDefault(); });
The problem is that preventDefault does nothing ... I reviewed most of the issues related to this issue in Stackoverflow, and checked my own jQuery documentation, but I can't seem to find what is wrong. I tried to add the async: false statement to the AJAX call, because maybe an asynchronous call might be a problem, but that doesn't fix it.
source share