m88k
m88k

Reputation: 23

Jquery Append On click function table

I am appending data to a table from an API call with jQuery. What i want to do now though is if someone clicks on a row in the table i want to pass the id of the row to another screen (edit screen) to edit the details of the row. When i try to add a click function to the row though it breaks as in the table doesn't populate with the data. what i've tried

option 1

$.get(...){
$.each(res.data, function (index, value) {
 $(".TData").append('"<tr id="'+value.id'"><td>'+value.description+'</td> <td>'+value.order+' </td> </tr>"')
})
}


$(".TData tr").click(function(event){
console.log(event.id); <- doesn't return value.id
(in reality this will redirect to the next page passing the id)
})

and in line assignment of onclick

$.get(...){
$.each(res.data, function (index, value) {
 $(".TData").append('"<tr onclick="rowClick(e)" id="'+value.id'"><td>'+value.description+'</td> <td>'+value.order+' </td> </tr>"')
})
}


function rowClick...

neither of these approaches worked, in that the table didn't populate with option 2. and under options 1 the id is never pushed into the console to do anything with. can someone explain what i'm doing wrong? }

Upvotes: 2

Views: 751

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206505

  • Fix your strings '" or rather use Template Literals
  • Use JS Array.prototype.map() to create an Array of rows
  • Use jQuery's Object notation Element Options
  • Append only once after all your $rows array is populated (for better performance)
  • Use .on() method to assign click listener to each row (see example below)

const res = { // Just to fake the response
  "data": [
    {"id": 111, "description": "Lorem", "order": "Order 1"},
    {"id": 222, "description": "Ipsum", "order": "Order 2"}
  ]
};

const $rows = res.data.map(obj => $('<tr>', {
  id: obj.id,
  append: `<td>${obj.description}</td><td>${obj.order}</td>`,
  on: {
    click() {
      console.log(obj.id);
      // You can also use $(this) to reference the clicked row
    }
  }
}));

// Append only once:
$(".TData").append($rows);
<table>
  <thead>
    <tr><th>Description</th><th>Order</th></tr>
  </thead>
  <tbody class="TData"></tbody>
</table>
<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>

MDN - Template literals
MDN - Array map
jQuery API - jQuery
jQuery API - .on()

Upvotes: 2

Related Questions