Home > Mobile >  How can I put each td value inside tr with $.each function in js?
How can I put each td value inside tr with $.each function in js?

Time:10-21

I have written a code in js to put each td value dynamically with in tr and code is as follows:

function salesList() {
    $.ajax({
        url: location.href   'sales',
        method: "post",
        success: function (response) {
            $("#data-table").html('');
            let data_keys = [];
            let output = "";
            data_keys = Object.keys(response.data[0]);
            $("#data-table").append("<thead><tr></tr></thead>");
            $.each(data_keys, function (key, value) {
                value = value.replace(/_/g, " ");
                $("#data-table>thead>tr").append("<td>"   value.toUpperCase(value)   "</td>")
            });

            $("#data-table").append("<tbody></tbody>");

            response.data.map(function (values) {
                output  = "<tr>"  
                    $.each(values, function (key, value) {
                        output  = "<td>"   value   "</td>"
                        console.log(value);
                    });
                  "</tr>";
            })
            $("#data-table>tbody").html(output);
        }
    });
}

But the problem is tr has been added in browser inspector, but td with value hasn't been added within tr in the table as shown bellow.

enter image description here

But console.log(value) is printing for td in browser console as shown bellow. Note: Here I have made screen shot of a portion of browser console console.log(value) output.

enter image description here

What is wrong in my code? Can any body correct it, please? Thank you.

const data = [{
  one: 'one'
}, {
  two: 'two'
}];
let output;

data.map(function(values) {
  output  = "<tr>"  
    $.each(values, function(key, value) {
      output  = "<td>"   value   "</td>"
      console.log(value);
    });  
  "</tr>";
})

$("#data-table>tbody").html(output);
<table id="data-table">
  <tbody></tbody>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

Rather than building up a string, create a jQuery row element and append the cells to it. Then append the row to the table body.

const data = [{
  one: 'one',
  two: 'two'
}, {
  three: 'three',
  four: 'four'
}];


data.map(function(values) {
  output = $("<tr>");

  $.each(values, function(key, value) {
    output.append($("<td>"   value   "</td>"));
  });

  $("#data-table>tbody").append(output);
});
td {
  background: pink;
}
<table id="data-table">
  <tbody></tbody>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related