Alex Dn
Alex Dn

Reputation: 5553

Reference JS object to DOM element

How can I reference specific DOM element to specific JS object? For example, i have an array of customers. Using jQuery, for each customer I create LI with checkbox and span for customers name. When checkbox is clicked, I need to do some processing on that customer JS object. The question, how i can get this JS object an easy way. Currently I have following:

$(customers).each(function(){
$("<li>").append($("<input type=\"checkbox\"").attr("id","chk_" + this.ID)).append($("<span>").text(this.Name)).appendTo("#ulCustomers");
});

$("#ulCustomers input[type=checkbox]").bind("click",function(){

var customerId = $(this).attr("id").replace("chk_","");
var CustomerObj = $(customers).filter(function () { return this.ID == customerId }).get(0);

myProcess(CustomerObj); //Two above two lines are just for select correct customer from array.
});

I believe in world of JS and jQuery exists more elegant way to do it. Thanks

Upvotes: 2

Views: 1515

Answers (3)

marcio
marcio

Reputation: 10512

I would use jQuery data, just like this:

$("checkbox").data('customer', this.ID);

To retrieve the data:

$("#ulCustomers input[type=checkbox]").bind("onchange",function(){

var customerId = $(this).data("customer");
var CustomerObj = $(customers).filter(function () { return this.ID == customerId }).get(0);

myProcess(CustomerObj); //Two above two lines are just for select correct customer from array.
});

Additionally, don't use click event on check-boxes, use onchange event ;)

Upvotes: 0

georg
georg

Reputation: 214949

You can use jquery data function

$(customers).each(function() {
    var elem = $("<li><input type='checkbox'><span>" + this.Name + "</span></li>").appendTo("#ulCustomers");
    elem.find("input").data("customer", this);
});

$("#ulCustomers input[type=checkbox]").click(function() {
    var CustomerObj = $(this).data("customer");
    myProcess(CustomerObj);
});

Upvotes: 2

Sam Greenhalgh
Sam Greenhalgh

Reputation: 6136

Could you not bind the click event to a closure with a reference to the relevant Customer object?

like this

$(customers)
.each(function(){
    var custObj = this;
    $("<li>")
        .append(
            $("<input type=\"checkbox\"")
            .append($("<span>")
            .text(this.Name))
            .appendTo("#ulCustomers")
            .bind("click", function(){
                myProcess(custObj);
            })
});

Upvotes: 1

Related Questions