Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change html data attribute value

$(document).ready( function () {

  $("#bla").on( "click", function () {
  
        alert( $(this).data('bla') );
  	    $(this).attr('data-bla', "2");  
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
  button
</div>

So, I need change data-bla value from "1" to "2", but as you can see, value not updated and every click on button, alerts default value "1".

What did I do wrong?

like image 769
Oto Shavadze Avatar asked Dec 10 '22 13:12

Oto Shavadze


1 Answers

data() is not an accessor function for data-* attributes. It's an accessor for jQuery's data cache for the element, which is only initialized from data-* attributes.

If you want to read the data-bla attribute's value, use attr("data-bla"), not data("bla"). If you want to set the bla data item, use data("bla", newValue), not attr("data-bla", newValue).

E.g., use attr() for both get and set, or use data() for both get and set, but don't mix them, because they manage different things.

Using attr():

$(document).ready( function () {

  $("#bla").on( "click", function () {
  
        alert( $(this).attr('data-bla') );
  	    $(this).attr('data-bla', "2");  
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
  button
</div>

Using data():

$(document).ready( function () {

  $("#bla").on( "click", function () {
  
        alert( $(this).data('bla') );
  	    $(this).data('bla', "2");  
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
  button
</div>
like image 69
T.J. Crowder Avatar answered Jan 21 '23 04:01

T.J. Crowder