The jQuery .data() method allows you to use an element to store data for later use in a the program.

This may come in handy with a score for a game, keeping track of item numbers, selected options, etc.

When you use .data() to store information you specify a key and a value for that key. When you retrieve this data you only specify the key. Any element can be used to store this data. Different elements can store different data if you need to store other information. Using the .data() method does not replace other data stored in that object, it extends the data object. It will replace what is stored as the value for the key if written correctly.

You can not use undefined as a value.

An example of using the jQuery .data() method is as follows. This is a very simpe routine where clicking on the button, increases the score. The value for the score is kept in a <div id="storeScore">. The value is initally 0, but with each click the current value is retrieved, increased by 1, sent to another element for display. Then the #storeScore element is sent the new value.

Here is the script:

var startScore = 0;
$("#storeScore").data("score", startScore);
var showScore = $("#storeScore").data("score");
$("#result span").html(showScore);

$("#btn1").click(function(){
    var existScore = $("#storeScore").data("score");
    var newScore = existScore + 1;
    $("#storeScore").data("score", newScore);
    var showScore = $("#storeScore").data("score");
    $("#result span").html(showScore);
});

Here is the HTML:

<div id="storeScore"></div>
<button id="btn1">CLICK HERE TO INCREASE SCORE</button><br>
<h3 id="result">SCORE: <span></span></h3>

Here is the result: