0

I have a piece of code where elements are generated in a for loop (PHP). The code is:

for($i=0; $i < $count; $i++)
{
  $member = $my_array[$i];
  <td><span id="myspan"><input type="text" id="username" value="<?php echo $member; ?>" /></span></td>
}

In my jquery code, I am trying to read the value of the clicked element but it is returning the value of the first element and not the value of the clicked element. I guess this is happening because the id of each element is the same. But then how to get the value of the clicked element?

My jQuery code is:

$("#myspan").click(function(){
alert(username);
});

Any pointers will be much appreciated?

coderatlarge
  • 577
  • 3
  • 8
  • 23

3 Answers3

0

Instead of giving each element the same id, give them all the same class, e.g.

<span class="myspan" ...> ... </span>

Then target the elements by class instead of by id with jQuery, like:

$('myspan').click(function (event) {
    var input = $(event.target).find("input");
    alert(input.val());
}
jackarms
  • 1,343
  • 7
  • 14
0

change id to name <span name="myspan$i"> and get your span by name like this answer. finally move your click code inside for loop

for($i=0; $i < $count; $i++)
{
  $member = $my_array[$i];
  <td><span name="myspan"><input type="text" id="username" value="<?php echo $member; ?>" /></span></td>

$('[name="myspan$i"]').click(function(){
    YOUR CODE
});
}
Alireza
  • 126
  • 1
  • 14
0

Move the jQuery code inside the for loop and append each identifier with echo $I;

coderatlarge
  • 577
  • 3
  • 8
  • 23