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

1 Answer 1

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?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.