Reputation: 159
I have created one table/matrix, using javascript I want to print the index of table row and table data on click on table data
<html>
<head>
<title>Table Creation</title>
<script language="javascript" type="text/javascript">
function createTable()
{
document.write("<table >");
for (var x = 1; x < 10; x++) {
document.write("<tr >");
for(var y = 1; y < 10; y++) {
document.write("<td><button>index</button></td>");
}
document.write("</tr>");
}
document.write("</table>");
}
</script>
</head>
<body>
<button onclick="createTable()">Try it</button>
<div >
</div>
</body>
</html>
</html>
for example,for row1 alert should be((1,1),(1,2),(1,3)....),for row2 alert should be((2,1),(2,2),(2,3))
Upvotes: 2
Views: 290
Reputation: 1721
Try this:
replace your line
document.write("<td><button>index</button></td>");
by
document.write("<td><button onclick='getIndex(this)'>index</button></td>");
and add this function
function getIndex(elem){
alert(elem.closest('tr').rowIndex + ","
+ elem.closest('td').cellIndex);
}
Upvotes: 0
Reputation: 82
<html>
<head>
<title>Table Creation</title>
<script language="javascript" type="text/javascript">
function createTable()
{
document.write("<table >");
for (var x=1; x <10; x++) {
document.write("<tr >");
for(var y=1; y<10; y++) {
document.write("<td><button>("+x+","+y+")</button></td>");
}
document.write("</tr>");
}
document.write("</table>");
}
</script>
</head>
<body>
<button onclick="createTable()">Try it</button>
<div >
</div>
</body>
</html>
</html>
Upvotes: 0
Reputation: 96
Check this :
<html>
<head>
<title>Table Creation</title>
<script language="javascript" type="text/javascript">
function createTable()
{
document.write("<table >");
for (var x=1; x <10; x++) {
document.write("<tr >");
for(var y=1; y<10; y++) {
document.write("<td><button onclick='alertButton("+x+","+y+")'>index</button></td>");
}
document.write("</tr>");
}
document.write("</table>");
}
function alertButton(row, col){
alert('('+row+','+col+')');
}
</script>
</head>
<body>
<button onclick="createTable()">Try it</button>
<div >
</div>
</body>
</html>
</html>
Upvotes: 3