I created elements with classes from an AJAX call. I’m trying to bind a click event to these created object.
When I create an element with the same handler class as the AJAX create elements, it binds just fine. But when the handler elements are created from the AJAX call, they don’t bind to the .click function.
I suppose it has something to do with when the elements are loaded. Will I need something like a promise statement for the .click() function?
If needed, you here’s my code.
Create the elements
function runQuery(){
var url = 'http://www.nexthometown.com/index.php?option=com_singleprop&view=raw&format=raw';
$.ajax({
url: url,
dataType: 'json',
success: function(data){
$.each(data, function (key, value){
var agentuid = value[0];
var mlsnum = value[1];
var address = value[5] + ' ' + value[6] + ' ' + value[7];
var city = value[9];
var state = value[10];
var zip = value[11];
$('#ohs_table').append('<tr><td>' + mlsnum + '</td><td>' + address + ' ' + city + ' ' + zip + '</td><td><div class="media_button">QRCode</div><div class="f_button media_button" value="' + mlsnum + '">Flyer</div></td></tr>');
});
},
error: function(jqXHR, error, errorThrown) {
alert(jqXHR.responseText);
}
});
};
The .click Function
$('.f_button').click(function(){
$('#test').html('<h1>Hello!</h1>');
});
$('.f_button')returns a collection of elements that exist when you call the selector. It won’t take new elements into account.Use the event delegation syntax of
.on()and attach theclickevent to an already existing parent element: