Bind event to AJAX populated list items
Posted
by
AnPel
on Stack Overflow
See other posts from Stack Overflow
or by AnPel
Published on 2012-03-21T02:57:16Z
Indexed on
2012/03/21
5:29 UTC
Read the original article
Hit count: 132
JavaScript
|jQuery
I have an unordered list with no list items.
I get some information from the user, I run it through my database using AJAX and the servers sends back a JSON object response.
Then I append each list item I want to display to the list using something like
$('blabla').append('<li>information</li>')
My question is, since the li elements were not there at the time the DOM was ready, how can I bind a click event to them?
Here is my full code:
$(function(){
var timer;
$('#f').keyup(function(){
clearTimeout(timer);
timer = setTimeout(getSuggestions, 400);
});
})
function getSuggestions(){
var a = $('#f')[0].value.length;
if( a < 3){
if(a == 0){
$('#ajaxerror').hide(300,function(){
$('#loading').hide(300,function(){
$('#suggest').hide(300)
})
})
}
return;
}
$('#loading').slideDown(200,function(){
$.ajax({
url: '/models/AJAX/suggest.php',
dataType: 'json',
data: {'data' : $('#f')[0].value },
success: function(response){
$('#ajaxerror').hide(0,function(){
$('#loading').hide(100,function(){
$('#suggest ul li').remove();
for(var b = 0; b < ( response.rows * 3); b = b + 3){
$('#suggest ul').append('<li>'+response[b]+' '+response[b+1]+' '+response[b+2]+'</li>')
// MISSING SOME CODE HERE TO BIND CLICK EVENT TO NEWLY CREATED LI
}
$('#suggest').show(300)
})
})
},
error: function(){
$('#suggest').hide(0,function(){
$('#loading').slideUp(100,function(){
$('#ajaxerror').show(300)
})
})
}
})
})
}
© Stack Overflow or respective owner