Tick Twitch
Tick Twitch

Reputation: 566

Jquery getting new value after data attribute update

I am updating link attribute values via ajax response.but When i am again clicking the button/link getting old values instead of new value.

Below is my codes;

HTML

<div class="calendar-control"><a class="evecal-month-view-control fright next-month" href="#" data-month="2" data-year="2019">Next</a><span class="text-center month-name">January 2019</span><a class="evecal-month-view-control fright prev-month" href="#" data-month="12" data-year="2018">Previous</a></div>

And Jquery code.

jQuery(document).on('click', '.evecal-month-view-control', function(e){
    e.preventDefault();
    var month = jQuery(this).data('month');
    var year = jQuery(this).data('year');
    console.log(month);
    _getMonthCalendar(month, year);
});

var _getMonthCalendar = function(m, y){
    jQuery.ajax({
        type: 'POST',
        url: eventcaldata.ajaxurl,
        data: {
            action: 'ec_ajax_month_table',
            year: y,
            month: m,
            nonce: eventcaldata.nonce,
        },
        beforeSend: function(){
            console.log('sending...');
        },
        success: function(response){
            jQuery('.next-month').attr( 'data-month', response.nextmonth.month );
            jQuery('.next-month').attr( 'data-year', response.nextmonth.year );
            jQuery('.prev-month').attr( 'data-month', response.prevmonth.month);
            jQuery('.prev-month').attr( 'data-year', response.prevmonth.year);
        }
    });
}

First on .next-month class the data-month attribute value is 2 then it is changed to 3 after response.But When i am again clicking that button i am getting 2 value when it should be 3

Upvotes: 2

Views: 1641

Answers (2)

witheroux
witheroux

Reputation: 185

The .data() method on jQuery objects caches the value from the initial read. Subsequent call to .data() will first look in jQuery's data storage and send you that value. .attr() won't update the data storage, but will update the attribute in HTML. Use either .data() or .attr() but avoid mix and match.

Upvotes: 4

Taplar
Taplar

Reputation: 24965

Do not intermix this usage of attr() and data(). data() caches the value that it reads from the element, and does not update the attribute. So if you update with data, attr will not see it. Pick one or the other, and stick with it.

Upvotes: 1

Related Questions