4

$(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?

2
  • 2
    $(this).data("bla", 2); Commented Jan 9, 2017 at 16:07
  • attr.('data') != data.( Commented Jan 9, 2017 at 16:08

3 Answers 3

8

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>

Sign up to request clarification or add additional context in comments.

Comments

4

The attr() method just update the attribute which is visible in the element. To store the data in right way you need to use data() method with second argument as the value.

$(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>

Refer : jQuery Data vs Attr?

Comments

2

If you check for .data('bla'), you should also change that one ;-)

$(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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.