2

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

3 Answers 3

2

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);
});
Sign up to request clarification or add additional context in comments.

Comments

1

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);
            })
});

1 Comment

Yep it's the easiest way, but i'm trying to avoid closures of such type :)
0

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 ;)

1 Comment

I think to store ref to whole customer obj in data will be more effectively than just id. I know onchange exists, but i preffer to use onclick and then to check if it checked :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.