I am trying to build a table dynamically from the javascript which runs is already in Aura component.

tableBody = tableBody + '<tr>';
tableBody = tableBody + '<td><a href="javascript:void(0)" id="' + datas[i].Id + '" data-recname ="' + 
            datas[i].Name + '"  onclick="selectedRow(this)">' + datas[i].Name + '</a></td>';

When I tried to build the same in LWC javascript as

<td><input type="checkBox" data-selectedrec="'+data[i]['Id']+'" onclick="{selectedRow}"></input> </td>

Dom gets created and getting an checkbox input but onclick function is not getting added in the DOM. What am I missing here?

  • Is there any reason you are not using lightning-datatable. Anyway, you need to add the event listener using js. check this Jul 31 '20 at 13:08

If you want to build elements properly, you need to use document.createElement and Element.addEventListener. If you don't want to do this manually, you should be able to import jQuery and do it that way. The reason why you can't just innerHTML events is because such methods may be able to bypass Locker Service restrictions.

  • 1
    If you programmatically add the listeners you are also responsible for programmatically unregistering them at the end of the component's life. Even then you may find some apparently strange issues because of the way LEX doesn't immediately destroy components when switching "record page" between multiple records of the same type. See this answer for details.
    – Phil W
    Jul 31 '20 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.