How to store data using jQuery
Posted: Mon Mar 01, 2010 1:22 am
The jQuery data functions provide a clean way to store information for any kind of use. You can assign any amount of data to an element on the page and access it later by referencing the element. Like everything in jQuery, this is very easy to use.
In the following examples, we will be using an element with the id db to store information about fruit.
Store something:
Fetch something:
Remove something:
In the following examples, we will be using an element with the id db to store information about fruit.
Store something:
Code: Select all
// Store the current fruit
$("#db").data("fruit", "orange");
// Store an array of fruit info
$("#db").data("orange", { type: "citrus", color: "orange" } );
Code: Select all
// Find out what the current fruit is
var fruit = $("#db").data("fruit"); // orange
// Get the type of the current fruit
var type = $("#db").data("orange").type; // citrus
Code: Select all
// Remove all fruit data
$("#db").removeData("fruit").removeData("orange");