I need to upgrade from "onclick" to "eventListener" but I need to keep the passing of arguments. How do I pass arguments when using "eventListener"? The following is the HTML and JavaScript code. Thanks.
<tbody>
<?php
$query = mysqli_query($conn, "SELECT id, nombre, signo_solar FROM horoscopos") or die (mysqli_error($conn));
if (mysqli_num_rows($query)==0){
echo "<td colspan='3'>No hay horóscopos que mostrar. Prueba a añadir uno en 'Crear entrada' del menú superior.</td>";
}else{
while ($row = mysqli_fetch_array($query)) { // Mientras haya elementos en el array
echo "<tr>";
echo "<td>$row[nombre]</td>";
echo "<td>$row[signo_solar]</td>";
echo "<td>
<button class='btn btn-danger' id='EditButton' onclick='editEntry($row[id])'>Editar</button>
<button class='btn btn-danger' id='DeleteButton' onclick="deleteEntry($row[id],'$row[nombre]','$row[signo_solar]')">Eliminar</button>
</td>";
echo "</tr>";
}
}
?>
</tbody>
the javascript:
function editEntry(id){
...
}
function deleteEntry(id, nombre, signo){
...
}
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("EditButton").addEventListener("click", editEntry);
document.getElementById("DeleteButton").addEventListener("click", deleteEntry);
})
2
Answers
You don’t pass arguments when using unobtrusive event handlers. Instead you can use
data
attributes to store your metadata within the element and read it back when the event fires.In addition, note that you should never use
id
attributes when looping to create repeated content. It will cause duplicates which is invalid. You should use a commonclass
in this case.Here’s a working example with the above guidelines implemented:
Here is the reference implementation for you.
And the JS will be: