Home » Jquery » With jQuery, update the value of a data element attribute

With jQuery, update the value of a data element attribute

Posted by: admin February 22, 2020 Leave a comment

Questions:

How can I update the value of a data element attribute ?

This is my HTML:

<a href="" data-action="add-to-cart">Add</a>

This is my JS:

$('a[data-action="add-to-cart"], a[data-action="remove-from-cart"]').click(function(e) {
    e.preventDefault();

    if($(this).data('action') == 'add-to-cart') {
        $(this).data('action', 'remove-from-cart');
    }

    else {
        $(this).data('action', 'add-to-cart');
    }
});

Thanks.

How to&Answer:

So I read on SO, and I found a solution that works for my case:
https://stackoverflow.com/a/41585821/9603642

$('a[data-action="add-to-cart"], a[data-action="remove-from-cart"]').click(function(e) {
    e.preventDefault();

    if($(this).data('action') == 'add-to-cart') {
        $(this).attr('data-action', 'remove-from-cart');
        $(this).data('action', 'remove-from-cart');
    }

    else {
        $(this).attr('data-action', 'add-to-cart');
        $(this).data('action', 'add-to-cart');
    }
});

I add to use attr and data.

Answer:

How to set any attribute in jquery:

$(this).attr('data-action', 'add-to-cart');