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>
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.
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.
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.
var table = document.getElementById("myTable");
table.addEventListener("click", function(e) {
if (e.target && e.target.nodeName == "TD") {
alert('Cell clicked')
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With