Search code examples
jqueryclickonclicklistener

jquery isn't getting dynamically updated data from button


I've created a button, which updates the values of itself, and when clicked on (again), jquery isn't picking up the updated values..

Before first click:

<a href="news" data-start="2" data-limit="2" data-page="2" class="btn load-more">Load more</a>

The jQuery:

$(document).on('click','.load-more',function(e){
        e.preventDefault();

        var start   = $(this).data('start'),
            limit   = $(this).data('limit'),
            page    = $(this).data('page'),
            type    = $(this).attr('href');

        alert( start+' '+limit+' '+page );

        $.ajax({
            url:'/index.php?route=news/news/getnext&start=4&limit=4&page=2',
            method:'GET',
            data:{start:start,limit:limit,page:page},
            dataType:'json',
            success:function(data){

                .... doing stuff ....

                if(data.pagination === true){
                    $('.load-more').attr('data-start',data.start).attr('data-limit',data.limit).attr('data-page',data.next);
                } else {
                    $('.load-more').fadeOut(250,function(){
                        $(this).remove();
                    });
                }

            }
        })(data);
    });

This alerts "2 2 2" as expected.

The updated button (after the first click):

<a href="news" data-start="4" data-limit="2" data-page="3" class="btn load-more">Load more</a>

Then I click the button again, and it still alerts "2 2 2", instead of "4 2 3", which the button was updated to..

Any ideas on this? I can't seem to get it working, I've tried the basic click function and also delegate but it's not working as expected.


Solution

  • After update the below code:

     <a href="news" data-start="4" data-limit="2" data-page="3" class="btn load-more">Load more</a>
    
        $(document).on('click','.load-more',function(e){
        e.preventDefault();
    
        var start   = $(this).attr('data-start');
            limit   = $(this).attr('data-limit');
            page    = $(this).attr('data-page');
    
    
        alert( start+' '+limit+' '+page );
    });