3

I have an array of JavaScript JSON objects which is being parsed from a JSON formatted-string. Now what I'm doing is that I'm looping through the array and append the data to a table within the page.

jQuery Code:

$.each(objArr, function(key, value) {
  var tr = $("<tr />");
  $.each(value, function(k, v) {
    tr.append($("<td />", {
      html: v
    }));
    $("#dataTable").append(tr);
  })
})

The code works perfectly and the table is getting populated successfully

But what I'm looking for is that, I want to add a delete button at the end of the row, by which the user will delete the row, and it also important to handle the click event in order to perform the required action

I've done this in another way, but it is not that efficient, I want to use the code above to accomplish that as it is more efficient:

for (var i = 0; i < objArr.length; i++) {
  var tr = "<tr>";
  var td1 = "<td>" + objArr[i]["empID"] + "</td>";
  var td2 = "<td>" + objArr[i]["fname"] + "</td>";
  var td3 = "<td>" + objArr[i]["lname"] + "</td>";
  var td4 = "<td>" + objArr[i]["phone"] + "</td>";
  var td5 = "<td>" + objArr[i]["address"] + "</td>";
  var td6 = "<td >" + objArr[i]["deptID"] + "</td>";
  var td7 = "<td>" + objArr[i]["email"] + "</td>";
  var td8 = "<td>" + '<button id="' + objArr[i]["empID"] + '" value="' + objArr[
      i]["empID"] + '" onclick="onClickDelete(' + objArr[i]["empID"] +
    ')">Delete</button>' + "</td></tr>";
  $("#dataTable").append(tr + td1 + td2 + td3 + td4 + td5 + td6 + td7 + td8);
}

Any suggestions please?

2 Answers 2

3

Try something like this:

$.each(objArr, function (key, value) {
                var tr = $("<tr />");
                $.each(value, function (k, v) {
                    tr.append($("<td />", { html: v }));
                    tr.append("<button class='remove' />");
                    $("#dataTable").append(tr);
                })
            })

This shall append the button at the end of the tr with class remove.

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

2 Comments

This will append the button after each td, so in each row I will have 6 buttons as I have 6 cells. anyways, your solution led me to the solution, I just moved $("#dataTable").append(tr); from the inner loop to the end of the outer loop. Thanks dear
Well, you don't really have to thank me, if my answer helped you then you may upvote or accept the answer.
1

Try this, I've include event handler for the each buttons inside the table.


CHANGES:

  • Adding Event Listener for each buttons inside the table.
  • Call method (function) with parameters.

Note: I am using, fadeOut method for fading purposes only. So you can see the changes. You can change the script as your need.


EXPLAINS :

  • var cRow = $(this).parents('tr'); on this line we have $(this) which mean we've select the button object that you've clicked, and search the parent with tag-name tr. We need to do this because we need to take control of all data inside the tr object.
  • var cId = $('td:nth-child(2)', cRow).text(); has mean search second td object wich located on cRow object. And take the text from the selected td.

JQUERY REFFERENCES :


$(document).ready(function() {
  var jsonData = [
    {id: 'A01', name: 'Fadhly'},
    {id: 'A02', name: 'Permata'},
    {id: 'A03', name: 'Haura'},
    {id: 'A04', name: 'Aira'}
  ];

  $.each(jsonData, function(key, val) {
    var tr = '<tr>';
  
    tr += '<td>' + (key + 1) + '</td>';
    tr += '<td>' + val.id + '</td>';
    tr += '<td>' + val.name + '</td>';
  
    tr += '<td><button class="delete" data-key="'+ (key + 1) +'">Delete</button></td>';
  
    tr += '</tr>';
  
    $('tbody').append(tr);
  });
  
  $('button.delete').on('click', function() {
    var cRow = $(this).parents('tr');
    var cId = $('td:nth-child(2)', cRow).text();
    var intKey = $(this).data('key');
    
    cRow.fadeOut('slow', function() {
      doDelete(cId, intKey);
    });
  });
  
  function doDelete(param1, param2) {
    alert('Data with\n\nID: [' + param1 + ']\nKey: [' + param2 + ']\n\nRemoved.');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table border="1" width="100%">
  <thead>
    <tr>
      <th>#</th>
      <th>Id</th>
      <th>Name</th>
      <th>Action</th>
    </tr>
  </thead>
  
  <tbody>
  </tbody>
</table>

4 Comments

Thanks, nice solution dear, but also I have another question, can I pass the some parameters to the handler? for example, I want to pass the id to the handler then use this id to a perform deletion process with the database, because the code you are implementing is just deletes the row from the html table, but when the user reloads the page it will appear again. hope my question is clear, and thanks again
Sure... but for fast respond purpose: In your scripts, you've write: var td8 = "<td>" + '<button id="' + objArr[i]["empID"] + '" value="' + objArr[i]["empID"] + '" onclick="onClickDelete(' + objArr[i]["empID"] + ')">Delete</button>' + "</td></tr>"; so your parameter is only empID. take a look at my block of code: cRow.fadeOut('slow', function() {....}); you can call your method (function) inside those block. As an example I am call the alert. For your empID variable you can get from cId variable from mine.
Thanks dear for your update, it works fine now but with some tiny changes: $('#dataTable').on('click','button', function () { console.log('!!'); var crow = $(this).parents('tr'); var cid = $("td:nth-child(2)", crow).text(); var intkey = $(this).data('key'); crow.fadeOut('slow', function () { doDelete(cid, intkey); }); }) But could u please explain more these two lines? var cRow = $(this).parents('tr'); var cId = $('td:nth-child(2)', cRow).text();
@AliAlhamaly: Glad to help you dude.. and sorry for my late response. For syntax explains, you can check for my latest update on my answer :)

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.