skip to Main Content

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


  1. 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 common class in this case.

    Here’s a working example with the above guidelines implemented:

    const editButtonHandler = e => {
      const row = e.target.closest('tr');
      const rowId = row.dataset.rowid;
      console.log(`Editing rowId: ${rowId}`);
      // your logic here...
    }
    
    const deleteButtonHandler = e => {
      const row = e.target.closest('tr');
      const rowId = row.dataset.rowid;
      const rowNumber = row.dataset.rownumber;
      const rowSigno = row.dataset.signo;
      console.log(`Deleting rowId: ${rowId} / number: ${rowNumber} / signo: ${rowSigno}`);
        
      // your logic here... AJAX?
      
      row.remove();
    }
    
    document.querySelectorAll('.edit-button').forEach(btn => btn.addEventListener('click', editButtonHandler));
    document.querySelectorAll('.delete-button').forEach(btn => btn.addEventListener('click', deleteButtonHandler));
    <table>
      <tbody>
        <tr data-rowid="id1" data-rownumber="num1" data-signo="foo">
          <td>1</td>
          <td>signo_solar 1</td>
          <td>
            <button class="btn btn-danger edit-button">Editar</button>
            <button class="btn btn-danger delete-button">Eliminar</button>
          </td>
        </tr>    
        <tr data-rowid="id2" data-rownumber="num2" data-signo="bar">
          <td>1</td>
          <td>signo_solar 2</td>
          <td>
            <button class="btn btn-danger edit-button">Editar</button>
            <button class="btn btn-danger delete-button">Eliminar</button>
          </td>
        </tr>
      </tbody>
    </table>
    Login or Signup to reply.
  2. Here is the reference implementation for you.

    <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' data-id='"+$row[id]+"'>Editar</button>
              <button class='btn btn-danger' id='DeleteButton' data-id='"+$row[id]+"' data-nombre='"+$row[nombre]+"' data-signo='"+$row[signo_solar]+"'>Eliminar</button>
              </td>";
        echo "</tr>";
    }
    }
    ?>
    </tbody>
    

    And the JS will be:

    function editEntry(event: MouseEvent){
        var id = event.target.getAttribute("data-id");
    }
    function deleteEntry(event){
        var id = event.target.getAttribute("data-id");
        var nombre = event.target.getAttribute("data-nombre");
        var signo = event.target.getAttribute("data-signo");
    }
    
    document.addEventListener('DOMContentLoaded', (event) => {
        document.getElementById("EditButton").addEventListener("click", editEntry);
        document.getElementById("DeleteButton").addEventListener("click", deleteEntry);
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search