Reputation: 19582
I have an html
table and in one of the columns I have a check-box
.
So each row has a checkbox
.
I have a javascript function that is triggered by the onclick
.
Now what I need is to do something specific with the specific row that the check-box was clicked.
E.g. if I clicked the check box on row 13 I want to be able to do something with the row 13 of the table. The something I want to do is replace an html element with another.
I have tried and saw that I can use document.getElementsByName
or document.getElementById
but it uses either the name
or the id
value.
But for a dynamically generated table I am not sure how to do this. I mean how to associate name
or id
to solve this.
What is the way to solve this problem?
Upvotes: 0
Views: 125
Reputation: 324800
Ignore all the other people answering blindly...
From my understanding of your question, you have ONE onclick handler on the table itself, and you want to get the row it happened on.
In such a case, you would do this:
yourtable.onclick = function(e) {
e|e=window.event;
var t = e.srcElement || e.target;
while(!t.tagName || t.tagName != "TR") t = t.parentNode;
// t is now the row that the click happened on
}
If, on the other hand, you actually have an onclick event on each checkbox, then... well, actually you can use the exact same code. ^_^
Upvotes: 4
Reputation: 58324
I'm not sure how you generated your table, but one thing you could do is use an id for the cell or row I care about and incorporate the row number in the id. For example, set row 13's id to "row_13". Then in javascript (the onclick event to be exact) you can parse the 13 out of the id. Or easier, incorporate the row number into the id of the checkbox itself (the row number that the checkbox is in) and then you don't have to hunt down the checkbox' parent using javascript.
Upvotes: 0
Reputation: 7442
One way of doing this is the following
<tr>
<td>
<input type="checkbox" onClick='myOnClickHandler(event, this)' />
</td>
</tr>
-
function myOnClickHandler(evt, obj){
// here obj refers to that specific checkbox which was clicked
var row = obj.parentNode.parentNode; // this way you can access specific row that is clicked
}
Upvotes: 7