0

Any idea why this doesnt work?

$( "#trn_one" ).prepend( '<div class="panel-group"> <div class="panel panel-primary"><div class="panel-body" id="panel_trn_1" style="color:black; text-shadow: none; text-align: center; height: 70px;">This is the beginning of the training for GeoNode platform. Click the NEXT button and follow the instrucitons to explore the platform. <br/> <br/> </div> <button type="button" id="next_trn" class="btn btn-primary" data-step=1> Next </button><br/> <br/></div>' );


$("#next_trn").on("click", function() {
  alert("it doesnt change the data attribute");
  $('#next_trn').data('step','2'); 
});

I try to change the data-step attribute of the button. But doesnt work.

user1919
  • 3,818
  • 17
  • 62
  • 97
  • 3
    Because [`data`](http://api.jquery.com/data) doesn't change attributes. See the linked question's answers for details. If you actually want to change an attribute, use [`attr`](http://api.jquery.com/attr): `$('#next_trn').attr('data-step','2');` – T.J. Crowder Oct 12 '17 at 11:42
  • Hmm. I don't want to use attr. I thought I am using data all the way. – user1919 Oct 12 '17 at 11:46
  • If you want to change the attribute, you need to use `attr` (or the DOM's `setAttribute`). If you just want to set the `step` value in jQuery's data cache for the element, that's what `data` does -- but then everything *using* it has ot use jQuery's data cache, **not** the attribute. – T.J. Crowder Oct 12 '17 at 11:54
  • @Crowder I understand that. What I miss is what I am doing wrong. I think I set the step value correctly or? – user1919 Oct 12 '17 at 11:55
  • I said what you're doing wrong in the first comment above, as do the various answers to the linked question: `data` doesn't change attributes. `data("step", ...)` has zero effect on the `data-step` attribute on the element. – T.J. Crowder Oct 12 '17 at 11:59
  • So what the heck is this guy doing? https://stackoverflow.com/questions/7163234/setting-a-value-dynamically-for-data-attributes-using-jquery – user1919 Oct 12 '17 at 12:00
  • 1
    Changing the jQuery data cache, and not changing the attribute. Exactly what the code above does. – T.J. Crowder Oct 12 '17 at 12:00
  • OK. I got it now. But then why would I use the data() element? Its only for storing purposes. Not updating it.. – user1919 Oct 12 '17 at 12:03
  • 1
    For situations where you don't care about updating the attribute, you only care about using the data cache. – T.J. Crowder Oct 12 '17 at 12:04

0 Answers0