0

I have a button on my page, and on click it displays a dynamically created table. This is happening in a JS file. Part of the table creation is as follows-

table_body = '<table border="1">';
    table_body += '<tr>';
        table_body += '<th>';
        table_body += '';
        table_body += '</th>';
        table_body += '<th>';
        table_body += 'Name';
        table_body += '</th>';
        table_body += '<th>';
        table_body += 'Age';
        table_body += '</th>';
    table_body += '</tr>';
    for(var i=0;i<number_of_rows;i++){
        table_body+='<tr>';
            table_body += '<td>';
            table_body += i+1;
            table_body += '</td>';
            table_body += '<td>';
            table_body += name[i];
            table_body += '</td>';
            table_body += '<td>';
            table_body += '<a href="" id='+name[i]+'>Age Action</a>';
            table_body += '</td>';
        table_body+='</tr>';
    }
    table_body+='</table>';
document.getElementById("tableDiv").innerHTML = table_body;

I am using Joomla Seblod and I have a div called tableDiv, and I'm replacing that div on the page with my created table after button click. I'm not able to track clicks (and then do other stuff) on Age Action above, from the same JS file. On the same file I have-

jQuery("#55").click(newTestFunction); //I have a console.log in newTestFunction

id=55 in the first Age Action row. Is it because it's being dynamically generated? I have added the id attribute that should be different for different rows of it, but when I click on any one of them, it's not logging the console message that I have on click.

I also checked the page source and it does not show any of the elements of the table. How/where can I track any click on the element? Any help will be appreciated.

manishk
  • 526
  • 8
  • 26
  • You need to use event delegation (i.e. `on()`) for dynamic content. Furthermore, you should not be mixing native JS with JQuery. – EternalHour Oct 29 '19 at 22:13

2 Answers2

1

The click event must be after this line:

document.getElementById("tableDiv").innerHTML = table_body;
jQuery("#55").click(newTestFunction); //I have a console.log in newTestFunction

That way the "#55" element will exists when you add the event to it.

Amós Assis
  • 161
  • 5
0

The selector you're using doesn't match the Age Action link elements.

Try changing this line:

<a href="" id='+name[i]+'>Age Action</a>

...to this:

<a href="" id=name' + i + '>Age Action</a>

And prepending 'name' before the number in your selector:

jQuery("#name55")

Some things to note:

  • An element id cannot start with a digit in valid HTML.
  • This syntax: name[i] is actually an index into an array variable named 'name'
jared
  • 58
  • 6