I have a table and I want to grab the information of each row when they are clicked.
But when I click on first row,i got the information while doing console.log(myArray[a]); but when i suddenly click 2nd row then onclick event is not trigerred.Since the 2nd row also has class 'box', i am not getting any information of this row in console.
window.onload=build;
var myArray=['suju','ruju','bhawana'];
var el=document.getElementById('message');
function build(){
var html="<h1>My friend list</h1><table>";
for(var x=0;x<myArray.length;x++){
html +='<tr data-row="'+x+'"><td>'+myArray[x]+'</td><td class="box" >'+(x+1)+'</td><td></td></tr>';
}
html +='</table>';
document.getElementById('output').innerHTML=html;
var ek=document.querySelectorAll('#output .box');
var a;
for(var i=0;i<ek.length;ek++){
ek[i].onclick=function(){
a=this.parentElement.getAttribute('data-row');
console.log(myArray[a]);
}
}
}
td{
border: 1px solid black;
padding: 10px;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="message">Comple JS</div>
<div id="output"></div>
</body>
</html>
Why is the 2nd row and 3rd row's onclick function not trigerred?
for(var i=0;i<ek.length;ek++)
you are incrementingek
– Hamza El Aoutar