I am wondering why i cannot execute a jquery function on a button loaded with .loaddata function.
<div id="products"></div>
<script>
$(document).ready(function(event) {
loadData(1,'default');
});
function loadData(page,type){
var base = '<?php echo $sr_class->baseURL();?>';
$.ajax
({
type: "GET",
url: base+"includes/module/loadProduct.php",
data: {page:page,type:type},
success: function(msg)
{
console.info(msg);
$("#products").html(msg);
}
});
}
$('.addcart').click(function(e){
e.preventDefault();
var proid = $(this).attr('proid');
var base = '<?php echo $sr_class->baseURL();?>';
$.post(base+'includes/module/addtocart.php',{p_id:proid, p_qty:1},function(result){
location.reload();
})
});
</script>
the 'msg' return from loadData function is :
<p><a proid="ABCD1001" class="btn btn-success addcart" role="button"> ABCD1001</a></p>
When i click the button, it did not execute the function.
That's because you're using .click()
instead of .on()
. The click()
binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on()
.
From the documentation of .on()
:
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
So bind .addcart
element with .on()
like this:
$(document).on('click','.addcart',function(e){
e.preventDefault();
var proid = $(this).attr('proid');
$.post('<?php echo $sr_class->baseURL();?>includes/module/addtocart.php',{p_id:proid, p_qty:1},function(result){
location.reload();
})
});