2

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? }

1 Answer 1

2
  • 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()

Sign up to request clarification or add additional context in comments.

2 Comments

Tried that but only the <try> parts getting inserted. Seems that everything afterwards is ignored
@Martin I have no clue what is your specific issue. <try>..? You mean <tr/>?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.