Home > Software design >  Getting Table row ID and Values in jQuery Array
Getting Table row ID and Values in jQuery Array

Time:01-28

In my web application, I created a table to show some items to the table. In the table, there are nine columns and the last has an editable cell.

enter image description here

The first column includes the Part_Id related to the Part No record and that field is hidden. So I want to get all the Id and data that does not contain the empty values in the `New Order Qty' column and pass all values to the controller.

So on the Create Order button click event, I tried to call this function to took Id and the Order Qty and add them to an array. But only the first record is going to the array. Is there a way to get only the records that contain values in the New Order Qty to array to pass it to the controller?

function createOrder() {

  var Orders = new Array();
  $("#tblParts").each(function() {

    var order = {};
    var partId = this.getElementsByTagName("td")[0];
    var pID = partId.innerText;
    var cellOrder = this.getElementsByTagName("td")[8];
    var cellOrderId = cellOrder.innerText;
    order.Id = pID;
    order.OrderQty = cellOrderId;
    Orders.push(order);

  });
}

CodePudding user response:

  1. IDs need to be unique
  2. You have jQuery, use it

const Orders = $("#tableId tbody tr").filter(function() {
  const cells = $(this).find("td");
  return cells.eq(8).text().trim() != ""
}).map(function() {
  const cells = $(this).find("td");
  return {
    [cells.eq(0).text().trim()]:  cells.eq(8).text()
  }
}).get()

console.log(Orders)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableId">
  <thead>
    <tr>
      <th>ID</th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th>QTY</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>ID 1</td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>32</td>
    </tr>
    <tr>
      <td>ID 2</td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>ID 3</td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>23</td>
    </tr>

  </tbody>
</table>

  •  Tags:  
  • Related