1

Hi there,

I'm having an issue with jQuery. I have an element, which contents I replace. However, I also replace the data-action attribute with another value. However, when I click on the element again, it still runs the code with the previous data-action attribute value. Is there a way to force jQuery to use the new one? Is this what I want even possible?

I Tried .data(), but with the same result.

jQuery

$('#selector li').click(function() {
    var action = $(this).data("action");
    var item = $(".item").data("id");
    $.ajax({
        type: "POST",
        data: "ticket=" + item,
        url: "/run/" + action,
        success: function(data) {
            var jsonObj = jQuery.parseJSON(data);

            if (jsonObj.valid == 'true') {
                if (action == 'pick') {
                    $('li[data-action=pick]').html('Release').attr('data-action', 'release');
                } else if (action == 'release') {
                    $('li[data-action=release]').html('Pick').attr('data-action', 'pick');
                }
            }
        }
    });
});

HTML

 <li data-action="pick">Pick</li>

Edit: I just think my previous comment was a bit unclear. I Want to change the attribute, which it does. However, when I click the element again, it still recognizes the previous attribute, and not the new one, thus not running the correct action.

Synthiatic
  • 261
  • 1
  • 16

2 Answers2

1
$('[data-action="pick"]').attr('data-action','release');

Doesn't work as you expect, At this point the data value has already been parsed into the jQuery data object from the node attribute.

To modify the data object you must use

$('[data-action="pick"]').data('action','release');

Note that the node attribute will remain unchanged if you wish to select it by the new selector in the future then apply both methods.

 $('[data-action="pick"]').attr('data-action','release').data('action','release');

That will then allow you to select it with $('[data-action="release"]')

See related: how would I store a javascript object as data attribute and edit it

andrew
  • 9,313
  • 7
  • 30
  • 61
0

As I pointed on comment:

try to use .data('action' , 'release') instead of .attr('data-action', 'release') and sure same for 'pick'

You can take a look at This Answer specially the part of don't intermix .data and .attr() calls. Use one or the other.

And while you'll use .html sure you'll need to Event binding on dynamically created elements?

$(document).on('click','#selector li',function(){
   // code here
});
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28