mercredi 22 juin 2016

How to use jquery to grab data-attribute in every button that was clicked

I am fairly new to jquery and I want to use it in my application. I have a table that contains some data like this:

<tbody>
 <tr>
  <td>Ariel <button id="edit" data-id="<?php echo $row->id_user; ?>Edit</button></td>
  <td>ariel@abc.com</td>
  <td>27</td>
 </tr>
 <tr>
  <td>Noel <button id="edit" data-id="<?php echo $row->id_user; ?>Edit</button></td>
  <td>noel@abc.com</td>
  <td>31</td>
 </tr>
 <tr>
  ...
 </tr>
</tbody>

I am trying to use jquery to grab data-id when <button> was clicked. This is my code :

$(function() {
  var btn = $("#edit"),
      id = btn.data("id");
  btn.on("click", function() {
    console.log(id);
  });
});

Only first row that can be logged. I don't know the syntax. What should i do?

@UPDATED@

I found a solution to use class instead of id. It is not valid to have the same id in some element. So i use this:

<button class="edit" data-id="<?php echo $row->id_user; ?>">Edit</button>

And make some changes in my jquery:

$(".edit").each(function() {
    var $this = $(this),
        id = $this.data("id");
    $this.on("click", function() {
      console.log(id);
    });
});

Aucun commentaire:

Enregistrer un commentaire