Nicolas Martinez Nicolas Martinez - 1 year ago 66
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">
Nombre Local
Hora de cierre
<?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>';

the JS

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

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);
error: function(xhr, textStatus, errorThrown) {

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download