jQuery's .data() Method

I was recently working on a project that required users to input numbers, formatted as currency into textboxes and then calculate said numbers with other formatted textboxes. My client-side calculator had 34+ textboxes. I was a bit worried that I'd need to create javascript variables for each of these textboxes and possibly as a number & formatted variable. Another requirement was if a user backspaces all of the numbers in a textbox, that it should return to it's original number.

Say Goodbye to Variables With jQuery's .data() Method

Having read up on jQuery's .data() method briefly in the documentation a few times in the past, I wondered to myself it that would be a possible solution. It a nutshell, the .data() method allows developers to store data inside elements in an array format. In the past I might have done something like this to store data:

<a href="/" rel="some data" rev="some more data" title="maybe even more data">Link With Data</a>

While this worked great there was a few drawbacks. For one it was improperly using attributes in a way the W3C spec never intended. Second I was limited to the amount of unique data I could store due to limits to the number of attributes at my disposal

Enter .data()

Going back to my original problem, with .data() I can now store data inside elements like so:

$("input").data("original", "$1.75"); $("input").data("currency", "$1.50"); $("input").data("decimal", 1.5);

To retrieve that data it's as simple as this:

$("input").data("original"); $("input").data("currency"); $("input").data("decimal");


jQuery also offers a shorthand method of assigning multiple values to a single element. Below is a shorthand variation of my above statements:

$("input").data("numbers",{original: "$1.75", currency: "$1.50", decimal: 1.5});

To retrieve these values it's also a bit different since they're now included in a single array called numbers

$("input").data("numbers").original; $("input").data("numbers").currency; $("input").data("numbers").decimal;

Removing Values

Below is jQuery's method of removing data:


Final Words

I found this technique to be easier to understand while I developed the application. Also, since I was already querying the element to get the user's input it was just another line of code to get other values I stored inside the element.

Further Reading

Feel free to check out jQuery's documentation on the .data() method. I also found a Firebug plug that allows you to inspect values assigned to elements which makes debugging easier.