Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add click event to table cell in this code?

Tags:

javascript

In this code, I want to make the table cell clickable with javascript.

Please also tell me how to use i,j values with the click event.

<!DOCTYPE html>
<html>
<head>
<style>
 td 
 {
   height : 30px;
   width : 30px;
   cursor: pointer;
 }
</style>

<script>
function clickHere(){
var table = document.getElementById("myTable");
var row ;
var cell;
for(var i=0;i<2;i++){
  row = table.insertRow(i);
  for(var j=0;j<2;j++){
    cell = row.insertCell(j);
  }
 }
}
</script>
</head>

<body onload="clickHere()">
 <table id = "myTable" border="1"></table>
</body>
</html>
like image 695
srikanth_k Avatar asked Jun 02 '16 10:06

srikanth_k


People also ask

How do I add a click event to a table?

There are two simple ways you can add an onclick event to Table cells dynamically using JavaScript. You can either use the setAttribute() method to assign or add an onclick event explicitly to a table cell, or you can use the addEventListner() method to capture click events on table cells.

What is click event coding?

An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.


2 Answers

Add this code:

cell.addEventListener("click",function(){
    alert("cell clicked");
});

After this code:

cell = row.insertCell(j);

It will add event listener to each cell. when clicked it will show an alert.

like image 127
Danny Ogen Avatar answered Oct 07 '22 07:10

Danny Ogen


var table = document.getElementById("myTable");

table.addEventListener("click", function(e) {
  if (e.target && e.target.nodeName == "TD") {
    alert('Cell clicked')
  }
});
like image 44
rishabh dev Avatar answered Oct 07 '22 06:10

rishabh dev