MSI MSI - 5 months ago 9
Javascript Question

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);
});
});

Answer

You cannot have same id multiple times in a single web page. Use class instead.

$(function() {
  var btn = $(".edit");
  
  btn.on("click", function() {
    var data = $(this).data("id");
    console.log(data);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<tbody>
  <tr>
    <td>Ariel <button class="edit" data-id="id-1">Edit</button></td>
    <td>ariel@abc.com</td>
    <td>27</td>
  </tr>
  <tr>
    <td>Noel <button class="edit" data-id="id-2">Edit</button></td>
    <td>noel@abc.com</td>
    <td>31</td>
  </tr>
  <tr>
    ...
  </tr>
</tbody>