Reputation: 7183
How to relate or associate an object in JavaScript to an HTML element?
For each object in an array, I generate a checkbox input element based on that object.
If I add an event listener to capture the checkbox changes, how do I retrieve the object associated with that element?
Upvotes: 3
Views: 2673
Reputation: 349042
Create a global object, store additional objects when you're creating the checkboxes, identified by a unique name. Set the name or id attribute of the checkbox element to this unique name.
var source = [];
var data = []; //Your data
var appendTo = document.body;//Anywhere
for(var i=0; i<data.length;i++){
var identifier = "chk"+i;
var inp = document.createElement("input");
inp.type = "checkbox";
inp.name = identifier;//.name or .id - it's up to your preference
inp.addEventListener("change", function(ev){
if(this.checked){
callback(source[this.name]);//calls function callback, passing the original object as an argument.
}
}, true);
appendTo.appendChild(inp);
source[identifier] = ...//your object.
}
Upvotes: 1
Reputation: 6329
As other answers point out, generating a unique id for each DOM node allows you to use those as keys in an Object.
Another possibility is that many frameworks provide utilities for assigning data to DOM elements. For example, in jQuery you can do it by writing $(checkbox).data('mydata', obj)
or in YUI Y.one(checkbox).setData('mydata', obj)
.
Upvotes: 5
Reputation: 12294
You give a progressive ID to each checkbox, starting from "checkbox0", and when you click on a checkbox you check the relative ID number, which correspond to the object in array[x].
Here is a really simple example.
Upvotes: 1
Reputation: 2490
You can generate an ID for each of the checkboxes, and store the ID in the corresponding object. Then, in the event handler, you can get the ID of the changed checkbox and find the appropriate object based on that by iterating over the array.
To make it even easier to find the object, you can also map the IDs to objects (e.g. objectsByID[someID] = someObject
). With this approach, you don't even have to iterate over the array.
Example of how to create the objectsByID
map:
var objectsByID = {};
for (var i = 0; i < objects.length; i++) {
var id = "checkbox_" + i;
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("id", id);
// ...
objectsByID[id] = objects[i];
}
Upvotes: 1