How to store data using jQuery

Web programming topics
Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to store data using jQuery

Post by Neo » 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:

Code: Select all

// Store the current fruit
$("#db").data("fruit", "orange");
// Store an array of fruit info
$("#db").data("orange", { type: "citrus", color: "orange" } ); 
Fetch something:

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 
Remove something:

Code: Select all

// Remove all fruit data
$("#db").removeData("fruit").removeData("orange"); 
Post Reply

Return to “Web programming”