Nicolas Martinez Nicolas Martinez - 2 months ago 8
HTML Question

function from same class of dynamyc list

I'm Working with a list of items and I need to set a function on click a button, but the list is filled dynamically from a php script, The problem is when I click on the button, the first one is ok, display info, put the others, display the info from the first item

<div class="col-lg-12">
<table class="table">
<thead>
<th>
Nombre Local
</th>
<th>
Direccion
</th>
<th>
Hora de cierre
</th>
<th>
Informacion
</th>
</thead>
<tbody>
<?php foreach($list as $item){
echo '<tr>';
echo '<td>'.$item['name'].'</td>';
echo '<td>'.$item['addr'].'</td>';
echo '<td>'.$item['closing'].'</td>';
echo '<td><button class="btn btn-data detalle" data-id="'.$item['id'].'" data-tipo="'.$item['tipo'].'" onclick="GetLocalesMain()"</td>';
echo '</tr>';
'};?>
</tbody>
</table>
</div>


the JS

function GetLocalesMain(){
var informacion = $(".detalle");
var id = informacion.data('id');
var tipo = informacion.data('tipo');

console.log(id);
console.log(tipo);
$.ajax({
url: '../functions/procesa.php?item=' + id + '&tipo=' + tipo,
type: 'POST',
dataType: 'json',
data: {},
complete: function (xhr, textStatus){
},
success: function(data, textStatus, xhr){
console.log('json', data);
$(data).each(function(a){
muestraData(this);
});
},
error: function(xhr, textStatus, errorThrown) {
}
});
}

Answer

The issue is that you are getting all instances of ".detalle" e.g. var informacion = $(".detalle"); but you need to target the item clicked, you can do this quite simply using jquery (as you are using it anyway).

You could remove onclick="GetLocalesMain()" in your html and in the javascript place the contents of your GetLocalesMain function inside the following jquery click function:

$( ".detalle").click(function() {
  // function contents goes here
});

Then replace var informacion = $(".detalle"); with var informacion = $(this);

You should now get the clicked item and subsequently the right data.