views:

1149

answers:

3

I'm working on a page where I need to associate a list of objects with a row of a table, and I'm using jQuery.

jQuery.data seems to just associate a piece of data with a key, whereas I need more like

id=4,setting=2 id=3,setting=1 ...

I don't know how long the list could be, and it could be empty.

Is there a sensible way of doing this?

Thanks :)

+1  A: 

I haven't got a great amount of time to try it now, but instead of storing a simple string against the key, why not store an object against it?

To paraphrase the jquery docs...

$("div").data("blah", {id: 4,setting: 2});
var myBlah = $("div").data("blah");
var id = myBlah["id"];
var setting = myBlah["setting"];

Let me know how you get on.

belugabob
But I'm trying to store a list of the objects...
Fiona Holder
Sorry - I should have user the whole array. I can see that activa provided the same solution, but with an array, and that you've accteped it. I'm glad that you've got a solution up and running.
belugabob
Thanks for your help though :)
Fiona Holder
+6  A: 

You can store anything as jQuery data, so you could do this:

var myData = [ { id: 4, setting: 2 }, [ id:3, setting:1 ] };

$("#myitem").data("mydata", myData);

If you want to select something by id, you could do this:

var myData = {};

myData[4] = 2;
myData[3] = 1;

$("#myitem").data("mydata", myData);

Then you can access your settings like this:

var value = $("#myitem").data("mydata")[3]; // returns 1
Philippe Leybaert
It's worth noting that if you have the element it's much more performant to use `$.data(element,"mydata")` than `$(element).data("mydata")`
Jethro Larson
A: 

You can use arrays to store lists and JSON objects to store key-value pairs.

<div id="DIV1"></div>
<div id="DIV2"></div>
<div id="DIV3"></div>
<div id="DIV4"></div>
<table><tbody><tr id="TR1"><td><td/></tr></tbody></table>
<script type="text/javascript">
$(function() {
    $("#TR1").data("blah", [{id: 4, setting: 2}, {id: 3, setting: 1}]);
    $("#DIV1").text($("#TR1").data("blah")[0].id);
    $("#DIV2").text($("#TR1").data("blah")[0].setting);
    $("#DIV3").text($("#TR1").data("blah")[1].id);
    $("#DIV4").text($("#TR1").data("blah")[1].setting);
});
</script>
Joe Chung