I have a problem. I have a table full of data and each record in this table has 2 buttons, show y delete
. These buttons have to trigger a JS function that will make a request to the server. My problem is that I don't want to put onclick="show($paciente->id)"
in each record, since I don't think it's a good practice, but I have no idea how to know which button is being pressed, since they will all trigger the same function but send a id
different .
@foreach ($pacientes as $paciente)
<tr>
<th scope="row">{{ $paciente->id}}</th>
<td>{{ $paciente->nombre }}</td>
<td>{{ $paciente->apellidos }}</td>
<td>{{ $paciente->carnet }}</td>
<td>{{ $paciente->fecha_nacimiento }}</td>
<td>{{ $paciente->telefono }}</td>
<td>{{ $paciente->direccion }}</td>
<td>{{ $paciente->strikes }}</td>
<td><a href="#" id="showUser" onclick="showUser({{ $paciente->ID}})" class="showUser" ><i class="far fa-eye"></i> Ver</a></td>
<td><a href="#" id="deleteUser" class="deleteUser"><i class="far fa-trash"></i> Eliminar</a></td>
</tr>
@endforeach
I tried with JS something like that, but it didn't work.
let showButton = document.querySelector('.showUser');
// let deleteButton = document.getElementById('deleteUser');
showButton.forEach((element) => {
element.addEventListener('click', function(){
alert(element.value);
})
})
as you have it without JQuery it is fine I would only make a few changes
The changes I made to your code were:
the querySelector() method , I changed it to querySelectorAll() since the as you had it refers to the first element it finds, while querySelectorAll is in all the matches that there are in the dom
and the second change I made was to replace the value property with the getAttribute() method since Value is only for inputs, and using this method would allow you to pass the id into the element as an attribute and access it
You can use jQuery's on function to help you add events on elements that haven't been rendered yet.