views:

118

answers:

2

Hi,

I have a table of products on my page, each product has zero or more colors, the colors are shown as a list beneath the product. After the colors I have a button to add a color. The button will do an ajax call with the parent product id to a controller which will return a JSON object with color information. My problem is where to store the product id in the DOM, should I put it in a hidden field and use jquery in the click event of the "add color" to get to it? What is the best way to do this?

TIA,

John

EDIT: The page is initially rendered on the server so I don't want to use jquery to add the id's to the page.

A: 
$.data(document.body, 'myObject', 42);

would store an integer of 42 on the body element for instance. You can store and access any data that way. Access would be like

var answer_for_everything = $.data(document.body, 'myObject');
jAndy
I edited my question, it wasn't clear that I want the Id's to be rendered by the server and not on the client.
John Landheer
+1  A: 

The quick and dirty way would be to put it in an anchor tag's rel attribute. Or you can use the metadata plugin: http://plugins.jquery.com/project/metadata. It's capable of getting "data-something" attributes from an element. And the "data-something" attribute is valid for HTML 5 (more info).

So you can have your html look like:

<tr data-productid="123"><td>...</td></tr>

And on a click event:

var productId = $('tr-selector-here').metadata().productid;
Shiki