0

I have this table:

<html>
  <body>
    <table id="user-table">
      <tr >
        <th>First Name</th>
        <th>Last Name</th>
      </tr>
    </table>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"</script>
    <script src="get-users.js"></script>
    <script src="delete-user.js"></script>
  </body>
</html>

And this is get-users.js file where i populate the table:

let $userTable = $("#user-table");
let $xhr = $.ajax({
  method: "GET",
  url: "http://localhost:8080/user-rest-api",
  dataType: 'json'
});
    
$xhr.done(function (data) {
  for (let user of data) {
    $userTable.append(`
      <tr>
        <td> ${user.firstName}</td>,
        <td> ${user.lastName} </td>
        <td> <button class = 'delete-btn' value=${user.id}>Delete</button> </td>
      </tr>
    `);
  }
});

And in delete-user.js i just want to print user id, this is what i tried:

$('#user-table').on('click', '.delete-btn', function () {
  let userId = $(".delete-btn").val();
  console.log("User ID : " + userId);
});

But it only prints first id, how can i dynamically get value based on button that is clicked?

biberman
  • 5,606
  • 4
  • 11
  • 35
Nem Jov
  • 51
  • 1
  • 8
  • 1
    Try using $(this).val() instead of $(".delete-btn").val(); – osekmedia Jun 21 '21 at 19:59
  • @osekmedia Thank you, it works. But is this the right approach to get some value from table? – Nem Jov Jun 21 '21 at 20:02
  • 1
    while buttons can have values (I didn't know that!) you're better off passing (non-form-input) data through the data-attribute. `` and then `let id = $('button').data('id')` – Kinglish Jun 21 '21 at 20:15
  • I agree with @Kinglish, if it were me, i'd probably use the data tag but both approaches will work. If you us the data tag as he suggested you'll want to use $(this).data('id'); in your onclick. – osekmedia Jun 21 '21 at 21:17

1 Answers1

0

You have to use the keyword this in the event handler to catch the button that was clicked:

let userId = $(this).val();

Working example: (with some dummy data and an ordinary function call)

let $userTable = $("#user-table");
let users = [
  {
    id: '1',
    firstName: 'John',
    lastName: 'Doe'
  },
  {
    id: '2',
    firstName: 'Jane',
    lastName: 'Doe'
  }
];

function fillTable(data) {
  for (let user of data) {
    $userTable.append(`
      <tr>
        <td>${user.firstName}</td>,
        <td>${user.lastName} </td>
        <td><button class='delete-btn' value=${user.id}>Delete</button> </td>
      </tr>
    `);
  }
}

$('#user-table').on('click', '.delete-btn', function() {
  let userId = $(this).val();
  console.log("User ID: " + userId);
});

fillTable(users);
<table id="user-table">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
  </tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Alternatively you could create the table-row and -cells with createElement(). You even don't need jQuery for that and can do it with plain JavaScript. The advantage is that you can add the event listener directly in the first function. The disadvantage is that you have no event delegation and multiple event listeners instead, one for each button.

Working example:

let $userTable = document.querySelector("#user-table");
let users = [
  {
    id: '1',
    firstName: 'John',
    lastName: 'Doe'
  },
  {
    id: '2',
    firstName: 'Jane',
    lastName: 'Doe'
  }
];

function fillTable(data) {
  for (let user of data) {
    let row = document.createElement('tr');
    let firstName = document.createElement('td');
    let lastName = document.createElement('td');
    let delete_button = document.createElement('button');

    firstName.textContent = user.firstName;
    lastName.textContent = user.lastName;
    delete_button.value = user.id;
    delete_button.textContent = 'Delete';
    delete_button.addEventListener('click', function() {
      let userId = this.value;
      console.log("User ID: " + userId);
    });

    row.appendChild(firstName);
    row.appendChild(lastName);
    row.appendChild(delete_button);
    $userTable.appendChild(row);
  }
}

fillTable(users);
<table id="user-table">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
  </tr>
</table>

If you although want to use jQuery for that the code gets a bit simpler.

Working example:

let $userTable = $("#user-table");
let users = [
  {
    id: '1',
    firstName: 'John',
    lastName: 'Doe'
  },
  {
    id: '2',
    firstName: 'Jane',
    lastName: 'Doe'
  }
];

function fillTable(data) {
  for (let user of data) {
    let row = $('<tr></tr>');
    let firstName = $('<td></td>');
    let lastName = $('<td></td>');
    let delete_button = $('<button></button>');

    firstName.text(user.firstName);
    lastName.text(user.lastName);
    delete_button.val(user.id).text('Delete').on('click', function() {
      let userId = $(this).val();
      console.log("User ID: " + userId);
    });

    row.append(firstName);
    row.append(lastName);
    row.append(delete_button);
    $userTable.append(row);
  }
}

fillTable(users);
<table id="user-table">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
  </tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
biberman
  • 5,606
  • 4
  • 11
  • 35
  • Thank you for taking your time to code and explain, but is this the right approach to get some value from table? – Nem Jov Jun 21 '21 at 20:14
  • What do you mean with "*the right way*"? There are multiple ways to do that - this is one of them. If you specify it i could answer that... – biberman Jun 21 '21 at 20:18
  • I was just wondering if someone with a lot more experience would solved the problem this way? – Nem Jov Jun 21 '21 at 20:23
  • Why not, it is minimalist and simple and it works. Maybe you could create the table-row and -cells with `createElement()`. I will update my answer for a second example... – biberman Jun 21 '21 at 20:29
  • 1
    @NemJov - the _right way_ is mostly subjective. For instance, I like to put id's like this into the `` - like `` because it associates the whole row with a single user. Then on button click `` I have a listener set up `$('button.del').click(function(){ let id = $(this).closest('tr').data('id'); })` – Kinglish Jun 21 '21 at 21:35