0

Is it possible to pass the "id" parameter to the "onclick" function?

 for (var i = 0; i < items.length; i++)
             {
             var row = table.insertRow(0);
             row.onclick = (function() {
             var id = items[i].id;// here!
             });
             var cell = row.insertCell(0);
             cell1.innerHTML = items[i].title;
             }

When I click on row it says that items is undefined and I understand why, so I'm asking about other ways to get id parameter in onclick function. Also I'm thinking to keep id value in hidden cell

7
  • we don't know what items is, maybe this question helps Commented Nov 17, 2014 at 21:32
  • This question doesn't make sense... should look into clarifying.. Commented Nov 17, 2014 at 21:33
  • "items" is an array of objects with id and title properties Commented Nov 17, 2014 at 21:34
  • Try a console.log(items[i]) and show us the output, could also help. Commented Nov 17, 2014 at 21:34
  • If you can use jQuery then here is the answer to your question. stackoverflow Answer Commented Nov 17, 2014 at 21:39

1 Answer 1

3

Without using jQuery, I'd do something along these lines:

for (var i = 0; i < items.length; i++) {
    var row = table.insertRow(0);
    row.setAttribute("data-myID", items[i].id);
    row.onclick = (function() {
        console.log(this.getAttribute("data-myID"));
    });
    var cell = row.insertCell(0);
    //cell1.innerHTML = items[i].title;
}

full fiddle here: http://jsfiddle.net/hztkzcya/

Sign up to request clarification or add additional context in comments.

Comments

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.