-3

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.

roberto
  • 1
  • 2
  • 5
    Can you please elaborate on your issue here? Errors, what happens when you click the button, etc. Basically, what is wrong with what you've done – Sterling Archer Feb 19 '20 at 20:26
  • What you have [seems to work fine](https://jsfiddle.net/j08691/bdru85aq/4/) – j08691 Feb 19 '20 at 20:31

2 Answers2

0

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.

roberto
  • 1
  • 2
-6

How to set any attribute in jquery:

$(this).attr('data-action', 'add-to-cart');
mothmonsterman
  • 2,451
  • 3
  • 21
  • 28