Question

I have div with unique id and I'm trying to get that div id with jQuery

<div class="quantity" id="UNIQUE_ID">Quantity</div>

Everything works good, but after loading div with ajax - I just can't get id from loaded div.

$('.quantity').click(function() {       
    $.post('quantity.php', { id: $(this).attr('id') }, function(output) {
        $(this).html(output);
    }); 
}); 

Any ideas?

Was it helpful?

Solution

This should work

$('.quantity').click(function() {
    var that = this;        

    $.post('quantity.php', { quantityId: $(that).attr('id') }, function(data) {
        $(that).html(data);
    }); 
}); 

But this is how i'd write it

<div class="quantity" data-id='<?=$unique_id?>'>
    Quantity
</div>

$('.quantity').on('click', function() {
    var that = this;        

    $.post('quantity.php', { quantityId: $(that).data('id') }, function(data) {
        $(that).html(data);
    }); 
});     

And for dynamic divs

<div class="quantity" data-id='<?=$unique_id?>'>
    Quantity
</div>

$(document).on('click', '.quantity', function() {
    var that = this;        

    $.post('quantity.php', { quantityId: $(that).data('id') }, function(data) {
        $(that).html(data);
    }); 
});     

OTHER TIPS

The onclick binding to your div won't work once the div has been refreshed (it binded on document.ready() right?). The solution will be either to rebind the function to your element every time you change it (a bad one) or use the on() function of jquery. Example code:

$(document).on('click', '.quantity', function(){
    var id = $(this).attr('id');        

    $.post('quantity.php', { quantityId: id }, function(data){
        $('#'+ id).html(data);
    }); 
}); 

UPDATE: As discussed in comments, the on method should bind to the document as a whole and not the the class to actually work as the deprecated live() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top