Loop over table rows that have a data attribute

I have a table that shows the product codes through which the customer can enter the desired quantity.

    <tr data-code="TEST1" data-description="Test Product (EACH)" data-whqc="" >
      <td>
        TEST1
      </td>
      <td>
        Test Product (EACH)
      </td>
      <td>
        4
      </td>
      <td style="text-align: center">
        <input name="qty" type="text" class="qty" maxlength="5">
      </td>
    </tr>

      

There are many rows in the table and I want to send this data to an AJAX page to add these products to the cart.

How can I iterate over all the rows of a table with elements data-*

, add them to the array in the same way as the qty input?

+3


source to share


1 answer


var array = [];
    $("#tbl").find("tr[data-code]").each(function () {
        var qty = parseFloat($(this).find(".qty").val()) || 0;
        if (qty > 0) {
            array[array.length] = {
                Code: $(this).attr("data-code"),
                Description: $(this).attr("data-description"),
                Whqc: $(this).attr("data-whqc"),
                Qty: qty
            };
        }
    });

      

jsFiddle demo here: http://jsfiddle.net/7kykjg2m/1/



Explanation:

  • Create empty array
  • Iterate over all TR elements that have an attribute data-code

  • Parse qty to float (I use float because sometimes qty can be fractional, like liters of oil), but use || 0

    to set qty

    to 0 if the amount is empty / null or NaN

    .
  • If the count is greater than 0, add the item to the array as an object using JSON
  • When done, pass the array data to the server / service using $.ajax()

    or whatever, but you didn't provide the details on that side, so you didn't display the code to do that.
+2


source







All Articles