Reputation: 2917
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>
Upvotes: 5
Views: 19084
Reputation: 1
$("#myInput").val($(This).children().eq(0).text()); - above code (1) 'myInput' is id of input box where we display the selected table cell value. (2)'eq(0)'-> which denote ,cell position value display in required in input box.
Upvotes: -2
Reputation: 1743
var table = document.getElementById("myTable");
table.addEventListener("click", function(e) {
if (e.target && e.target.nodeName == "TD") {
alert('Cell clicked')
}
});
Upvotes: 3
Reputation: 289
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.
Upvotes: 9
Reputation: 3917
Add a click listener first and write a function with same listener name which will be executed after clicked. Try the code below:
<!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);
row.addEventListener('click', clickHandlerRow);
for(var j=0;j<2;j++){
cell = row.insertCell(j);
cell.addEventListener('click', clickHandlerColumn);
}
}
}
function clickHandlerRow(e) {
alert("row clicked");
}
function clickHandlerColumn(e) {
alert("column clicked");
}
</script>
</head>
<body onload="clickHere()">
<table id = "myTable" border="1"></table>
</body>
</html>
Upvotes: 0
Reputation: 1871
After the cell is added to the DOM you can add eventListeners to it. So the only thing you have to do, is add the eventListener :)
// here you add the cell and have a reference to it
cell = row.insertCell(j);
// now you can add eventlisteners to it
cell.addEventListener('click', function(){
console.log('cell clicked');
});
About adding event listeners: MDN
Demo: https://jsfiddle.net/kt9g8h4w/1/
Upvotes: 1