2

I have some html and script here:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {

    $("#options").attr("data-previousvalue1", $("#options").val());

        $("#options").data("previousvalue2", $("#options").val());
});
</script>
</head>
<body>
<select id="options">
    <option value="1">option 1</option>
<option selected="selected" value="2">option 2</option>
<select>
</body>
</html>

So, this only half works as I expect it to:

$("#options").attr("data-previousvalue1", $("#options").val());

sets data-previousvalue1=2 which is good

but I expected:

("#options").data("previousvalue2", $("#options").val());

to set data-previousvalue2=2.

Do I misunderstand the data method? From my searching and reading this should work.

Here's the output html:

enter image description here

AnonyMouse
  • 18,108
  • 26
  • 79
  • 131

1 Answers1

5

When using jQuery's data method, it's actually storing the value internally in a cache, that's not visible when inspecting the element. The data will be there if you call the data such as alert($("#options").data("previousvalue2"));

Please check out this article for further details.

How does jQuery .data() work?

Community
  • 1
  • 1
Bryan
  • 6,682
  • 2
  • 17
  • 21