jQuery Data method in ASP.NET

The jQuery data() method allows us to attaches data and then retrieve from, selected DOM elements. It stores arbitrary data which is associated with the matched elements.
  • 1613
 

The jQuery data() method allows us to attaches data and then retrieve from, selected DOM elements. It stores arbitrary data which is associated with the matched elements.

Syntax

$(selector).data(name)

The parameter name is optional which is used to specify the name of data to retrieve. If no name is specified, it will return all stored data for the element as an object.

In the following example you can get the data value stored at for an element.

Example

<!DOCTYPE html>
<html>
<
head><title>jQuery data method</title>  
  <style>  
    div { margin:5px; background:yellow;
        height: 29px;
        width: 150px;
    }  
    button { margin:5px; font-size:14px; }  
    p { margin:5px; color:red; }  span { color:blue; }
       .style1
    {
        color: #663300;
    }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</
head>
   <body bgcolor="#fff0ff">
      <div class="style1" 
         style="border: medium groove #066AFF; font-family: Verdana; font-size: medium; font-weight: bold;
                background-color: #DFECFF;">This is the div</div>
           <button style="font-family: Verdana; font-size: medium; width: 278px;">Get "data value" from the div</button>  
           <button style="font-family: Verdana; font-size: medium; width: 276px;">Set "value" to "Welcome&quot;</button>  
           <button style="font-family: Verdana; font-size: medium; width: 276px;">Remove "value" from the div</button>
             <p style="font-family: Verdana; font-size: medium; font-weight: bold">The "data 
                 value" of this div is <span>?.</span>
             </p>
  <script>
     $("button").click(function (e) {
        var value;
        switch ($("button").index(this)) {
           case 0: value = $("div").data("");
              break;
           case 1: $("div").data("", "Welcome."); value = "Stored!";
              break;
           case 2: $("div").removeData(""); value = "Removed!";
              break;
        }
        $("span").text("" + value);
     });
  </script>
 </body>
</
html>

Output

data1.gif

There is no value defined for the data in the above figure. Now we click on the second button to set the data value to welcome which is stored in the DOM.

data2.gif

Now click on the first button to get the stored data value as below figure shown.

data3.gif

Note: You can set several distinct values for a single element and retrieve them later.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.