I have a Laravel project that uses API calls. When the row is generated it has a edit button that has a modal popup. The modal used to work when it was static, but now when it's dynamically added i get the following error:
Modal with id editUserModal has not been initialized. Please initialize it using the data-modal-target attribute.
userTable ID:
<tbody id = "userTable">
//here is where i want it to be generated
//if i add a static row here the modal does work and i get no error
</tbody>
Here is the JavaScript function( i use axios ):
const drawUsers = () => {
let userTable = document.getElementById("userTable");
axios.get(API.url + API.routes.getUsers)
.then(response =>{
if(response.data.status){
response.data.data.forEach(user => {
var row = `<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<th scope="row" class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
${user.username}
</th>
<td class="px-6 py-4">
${user.email}
</td>
<td class="px-6 py-4">
${user.is_active}
</td>
<td class="px-6 py-4">
<button id = "editUserModal" data-modal-target="editUserModal" data-modal-toggle="editUserModal" class="focus:outline-none text-white bg-green-700 hover:bg-green-800 focus:ring-4 focus:ring-green-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-green-600 dark:hover:bg-green-700 dark:focus:ring-green-800">
Edit
</button>
<button type="button" class="focus:outline-none text-white bg-red-700 hover:bg-red-800 focus:ring-4 focus:ring-red-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-900">
Delete
</button>
</td>
</tr>`;
userTable.innerHTML += row;
});
}
})
}
I get generated everything correctly except the modal, what am i doing wrong? Is there a better way to dynamically generate HTML code with JavaScript?