Reputation: 37
I'm trying to add an onclick
event to a table column using JavaScript. For example, an onclick
event enabled on the first or second column! The following function is for rows, but I need to edit this function for specific columns.
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function (row) {
return function () {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
Upvotes: 3
Views: 21149
Reputation: 10714
Try this working soln.
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
currentRow.onclick = createClickHandler(currentRow);
}
}
function createClickHandler(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];// if you put 0 here then it will return first column of this row
var id = cell.innerHTML;
alert("id:" + id);
};
}
addRowHandlers();
Upvotes: 3
Reputation: 1487
This is the code to return row and column number using jQuery, it must be helpful Jsfiddle link
$('td').on('click',function() {
var col = $(this).parent().children().index($(this));
var row = $(this).parent().parent().children().index($(this).parent());
alert('Row: ' + row + ', Column: ' + col);
});
Upvotes: 1
Reputation: 8939
You can attach only the single onclick
handler to your table and then recognize the clicked column, this technique is called event delegation:
document.getElementById("tableId").onclick = columnHandler;
function columnHandler(e) {
e = e || window.event; //for IE87 backward compatibility
var t = e.target || e.srcElement; //IE87 backward compatibility
while (t.nodeName != 'TD' && t.nodeName != 'TH' && t.nodeName != 'TABLE') {
t = t.parentNode;
}
if (t.nodeName == 'TABLE') {
return;
}
var c = t.parentNode.cells;
var j = 0;
for (var i=0; i<c.length; i++){
if (c[i] == t) {
j = i;
}
}
alert('You clicked on row #'+(j+1)+ ' , cell content = '+t.innerHTML);
}
Upvotes: 0
Reputation: 1899
adding class to affected rows/columns would be more flexible.
if you know the rows/columns do something like this (untested), for rows 1 and 2:
var $table = jQuery('#tableId');
var $rows = jQuery('tr:nth-child(0),tr:nth-child(1)', $table);
$rows
.addClass('event-1')
.click(function()
{
// do what on click event
alert(jQuery(this).html());
});
Upvotes: 1