How to put only one table td into an array

Tags: ,



I have a table like this:

var markup = "<tr> " +
        "<td><center>" + count + "</center></td>"+
        "<td><center><input type='checkbox' name='record'></center></td>"+
        "<td>" + id_dept + "<input type='hidden' name='team"+count+"' value='" + team + "'></td>" +
        "<td style='border-right:0px;border-left:0'>" + name + "</td>"+
        "<td style='border-right:0px;border-left:0'><input  name='empid"+count+"' value='" + empid + "'></td>" +
        "<td style='border-right:0px;border-left:0'><input type='hidden' name='name"+count+"' value='" + name + "'></td>" +
        "<td style='border-right:0px;border-left:0'><input type='hidden' name='bgian"+count+"' value='" + bgian + "'></td>" +
    "</tr>";

$("table[id=table-pss] tbody").append(markup);

I want to put the td “empid” into an array. Here’s what I’ve done so far:

    var myTableArray = [];
    $("table[id=table-pss] tbody tr").each(function() {
        var arrayOfThisRow = [];
        var tableData = $(this).find('td');
        if (tableData.length > 0) {
            tableData.each(function() { 
                arrayOfThisRow.push($(this).text()); 
            });
           myTableArray.push(arrayOfThisRow);
        }
    });
    console.log(myTableArray);

It adds the whole td’s to array though, I’m wondering how to add only a td to array. thank you

Answer

You need assign an id to your empID input to be able to find it from the table.

For that you can use .find() function and to get the input value just use .val() function.

Live Demo:

var myTableArray = [];
$("table[id=table-pss] tr").each(function() {
  var tableData = $(this).find('td');
  var empID = tableData.find('#empID').val()
  if (tableData.length > 0) {
    myTableArray.push(empID);
  }
});

console.log(myTableArray); //["10"] empID
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:100%" id="table-pss">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>EmpID</th>
  </tr>
  <tr>
    <td style='border-right:0px;border-left:0'>Bob</td>
    <td style='border-right:0px;border-left:0'>Something</td>
    <td style='border-right:0px;border-left:0'><input id="empID" name='empid"+count+"' value='10'></td>
    <td style='border-right:0px;border-left:0'><input type='hidden' name='name"+count+"' value='" + name + "'></td>

  </tr>
</table>


Source: stackoverflow