0

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?

1
  • 4
    for(var i=0;i<ek.length;ek++) you are incrementing ek Commented May 20, 2020 at 13:41

1 Answer 1

1

for(var i=0;i<ek.length;ek++){ you are not incrementing i here, rather, ek, the array itself, which would have no effect.

Instead, replace the ending of the for loop with i++.

Alternatively you can use an array's forEach function which may be simpler, Array.apply(0, ek).forEach(x => /*code here*/);

Sign up to request clarification or add additional context in comments.

1 Comment

can u please also tell me where i can see .getAttribute() function. I did console.dir(this); but i didnot see any getAttribute() function? how can i know there is getAttribute function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.