如何使用 JQuery 从动态 html 表中获取选定的行值?

Posted

技术标签:

【中文标题】如何使用 JQuery 从动态 html 表中获取选定的行值?【英文标题】:How to get selected row values from a dynamic html table using JQuery? 【发布时间】:2021-04-10 20:16:20 【问题描述】:

我有一个使用 laravel 框架从数据库动态填充的 html 表。

我在行标题中放置了一个复选框和一个Save Entry 按钮。我只想获取表格的选中行值,包括指示计算摘要的表格页脚。

类似这样的:

arrbreakdown = []; //push here the checked row values.
arrsummary = []; //push here the calculation summary.

可重现的例子:

<table class="table table-bordered" id="purchasetable">
    <thead>
        <tr>
            <th colspan="7" class="bg-secondary">
                Item Breakdown
            </th>
        </tr>
        <tr class="text-center">
            <th scope="col"><input type="checkbox" onclick="checkallcabin(this)" name="checkall"
                    id="checkall"> </th>
            <th scope="col">Item Name</th>
            <th scope="col">Description</th>
            <th scope="col">Qty</th>
            <th scope="col">UM</th>
            <th scope="col">Item Price</th>
            <th scope="col">Total Price</th>
            <script>
                function checkallcabin(bx) 
                    for (var tbls = $('#purchasetable'), i = tbls.length; i--;)
                        for (var bxs = tbls[i].getElementsByTagName("input"), j = bxs.length; j--;)
                            if (bxs[j].type == "checkbox")
                                bxs[j].checked = bx.checked;
                    setselect();
                
            </script>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td> <input onchange="enablereqinfo()" id="row1" type="checkbox" name="dtrow"></td>
            <td>TEST 1</td>
            <td><input type="text" style="width:100%" value="TEST DESC 1"></td>
            <td>PCS</td>
            <td class="totalqty">5</td>
            <td><input type="number" step="0.01" style="max-width:100px;" value="0.00" onkeyup="calculateprice()" min="0"
                    class="iprice tnum" name="iprice"></td>
            <td class="totalprice text-right">0.00</td>
        </tr>
        <tr>
            <td> <input onchange="enablereqinfo()" id="row2" type="checkbox" name="dtrow"></td>
            <td>TEST 2</td>
            <td><input type="text" style="width:100%" value="TEST DESC 2"></td>
            <td>M</td>
            <td class="totalqty">7</td>
            <td><input type="number" step="0.01" style="max-width:100px;" value="0.00" onkeyup="calculateprice()" min="0"
                    class="iprice tnum" name="iprice"></td>
            <td class="totalprice text-right">0.00</td>
        </tr>
        <tr>
            <th colspan="6">Sub Total</th>
            <th class="text-right subtotal">0.00</th>
        </tr>
        <tr>
            <th colspan="6">Discount</th>
            <th class="text-right"><input style="max-width:100px;" onkeyup="calculatetotals()" type="number" value="0.00"
                    class="discount text-right"></th>
        </tr>
        <tr>
            <th colspan="6"></th>
            <th class="text-right taxtotal">0.00</th>
        </tr>
        <tr>
            <th colspan="6">Net Amount</th>
            <th class="text-right netamount">0.00</th>
        </tr>
        <tr>
            <th colspan="6">Grand Total</th>
            <th class="text-right grandtotal">0.00</th>
        </tr>
    </tbody>
</table>

这是我的 Html:

<table class="table table-bordered" id="purchasetable">
    <thead>
        <tr>
            <th colspan="7" class="bg-secondary">
                Item Breakdown
            </th>
        </tr>
        <tr class="text-center">
            <th scope="col"><input type="checkbox" onclick="checkallcabin(this)" name="checkall"
                    id="checkall"> </th>
            <th scope="col">Item Name</th>
            <th scope="col">Description</th>
            <th scope="col">Qty</th>
            <th scope="col">UM</th>
            <th scope="col">Item Price</th>
            <th scope="col">Total Price</th>
            <script>
                function checkallcabin(bx) 
                    for (var tbls = $('#purchasetable'), i = tbls.length; i--;)
                        for (var bxs = tbls[i].getElementsByTagName("input"), j = bxs.length; j--;)
                            if (bxs[j].type == "checkbox")
                                bxs[j].checked = bx.checked;
                    setselect();
                
            </script>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>

还有我的 jquery:

function getpurchasereqinfo(prid) 
    var val = (prid.value || prid.options[prid.selectedIndex].value);

    $.ajax(
            type: 'POST',
            url: '/dashboard/purchasing/quotation/get-prrequestinfo',
            data: 
                "refid": val,
                "transtype": $('#reqtype').val()
            ,
            encode: true,
            dataType: 'json',
            headers: 
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            ,
        )
        .done(function (data) 
            var cnt = 0;
            $("#purchasetable > tbody").empty();

            for (i in data.prrequestinfo) 

                cnt = cnt + 1;
                $("#purchasetable > tbody").
                append("<tr>" +
                    "<td> <input onchange='enablereqinfo()' id='row" + cnt +
                    "' type='checkbox' name='dtrow'></td>" +
                    "<td>" + data.prrequestinfo[i]['item_name'] + "</td>" +
                    "<td><input type='text' style='width:100%' value='"+ data.prrequestinfo[i]['idescription'] +"'></td>" +
                    "<td>" + data.prrequestinfo[i]['um'] + "</td>" +
                    "<td class='totalqty'>" + data.prrequestinfo[i]['quantity'] +
                    "</td>" +

                    "<td>" +
                    "<input type='number' step='0.01' title='Currency' pattern='^\d+(?:\.\d1,2)?$' onblur='this.parentNode.parentNode.style.backgroundColor=/^\d+(?:\.\d1,2)?$/.test(this.value)?'inherit':'red' step='.01' style='max-width:100px;' value='0' onkeyup='calculateprice()' min='0'  class='iprice tnum' name='iprice'>" +
                    "</td>" +

                    "<td class='totalprice text-right'>" + '0.00' + "</td>" +

                    "</tr>"
                );
            


            $("#purchasetable > tbody").
            append(

                "<tr>" +
                "<th colspan='6'>Sub Total</th>" +
                "<th class='text-right subtotal'>0.00</th>" +
                "</tr>" +
                "<tr>" +
                "<th colspan='6'>Discount</th>" +
                "<th class='text-right'><input style='max-width:100px;' onkeyup='calculatetotals()' type='number' value='0.00' style='width:100%; font-weight:bold;' class='discount text-right'></th>" +
                "</tr>" +
                "<tr>" +
                "<th colspan='6'></th>" +
                "<th class='text-right taxtotal'>0.00</th>" +
                "</tr>" +
                "<tr>" +
                "<th colspan='6'>Net Amount</th>" +
                "<th class='text-right netamount'>0.00</th>" +
                "</tr>" +
                "<tr>" +
                "<th colspan='6'>Grand Total</th>" +
                "<th class='text-right grandtotal'>0.00</th>" +
                "</tr>"

            );
        );

有什么想法吗?谢谢

【问题讨论】:

也显示你的 html 。 请提供一个最小的、可重现的例子:***.com/help/minimal-reproducible-example @Twisty,我已经更新了我的问题。 嗨,所以你需要在数组或整行中推送itemid 值? 带检查的行的所有项目值。并将计算汇总到另一个数组中。我突出显示了我要保存的数据。 【参考方案1】:

您可以遍历使用each 循环检查的所有复选框,然后使用.val().text()values 推送到数组中的行中

演示代码

$("#save").click(function() 
  var arrbreakdown = []; //push here the checked row values.
  var arrsummary = []; //push here the calculation summary.
  //loop through checked checkbox
  $("tbody input[type='checkbox']:checked").each(function() 
    var selector = $(this).closest('tr'); //get closest row
    //push values in array
    arrbreakdown.push(
      "Name": selector.find('td:eq(1)').text(),
      "Description": selector.find('td:eq(2) input').val(),
      "Qty": selector.find('td:eq(3)').text(),
      "UM": selector.find('td:eq(4)').text(),
      "Item_Price": selector.find('.iprice').val(),
      "Total": selector.find('td:eq(6)').text()
    )

  )
  //for summary
  arrsummary.push(
    "Sub_Total": $(".subtotal").text(),
    "Discount": $(".discount").val(),
    "taxtotal": $(".taxtotal").text(),
    "netamount": $(".netamount").text(),
    "grandtotal": $(".grandtotal").text()
  )
  console.log(arrsummary)
  console.log(arrbreakdown)

)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="purchasetable">
  <thead>
    <tr>
      <th colspan="7" class="bg-secondary">
        Item Breakdown
      </th>
    </tr>
    <tr class="text-center">
      <th scope="col"><input type="checkbox" onclick="checkallcabin(this)" name="checkall" id="checkall"> </th>
      <th scope="col">Item Name</th>
      <th scope="col">Description</th>
      <th scope="col">Qty</th>
      <th scope="col">UM</th>
      <th scope="col">Item Price</th>
      <th scope="col">Total Price</th>
      <script>
        function checkallcabin(bx) 
          for (var tbls = $('#purchasetable'), i = tbls.length; i--;)
            for (var bxs = tbls[i].getElementsByTagName("input"), j = bxs.length; j--;)
              if (bxs[j].type == "checkbox")
                bxs[j].checked = bx.checked;
          //setselect();
        
      </script>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> <input onchange="enablereqinfo()" id="row1" type="checkbox" name="dtrow"></td>
      <td>TEST 1</td>
      <td><input type="text" style="width:100%" value="TEST DESC 1"></td>
      <td>PCS</td>
      <td class="totalqty">5</td>
      <td><input type="number" step="0.01" style="max-width:100px;" value="0.00" onkeyup="calculateprice()" min="0" class="iprice tnum" name="iprice"></td>
      <td class="totalprice text-right">0.00</td>
    </tr>
    <tr>
      <td> <input id="row2" type="checkbox" name="dtrow"></td>
      <td>TEST 2</td>
      <td><input type="text" style="width:100%" value="TEST DESC 2"></td>
      <td>M</td>
      <td class="totalqty">7</td>
      <td><input type="number" step="0.01" style="max-width:100px;" value="0.00" onkeyup="calculateprice()" min="0" class="iprice tnum" name="iprice"></td>
      <td class="totalprice text-right">0.00</td>
    </tr>
    <tr>
      <th colspan="6">Sub Total</th>
      <th class="text-right subtotal">0.00</th>
    </tr>
    <tr>
      <th colspan="6">Discount</th>
      <th class="text-right"><input style="max-width:100px;" onkeyup="calculatetotals()" type="number" value="0.00" class="discount text-right"></th>
    </tr>
    <tr>
      <th colspan="6"></th>
      <th class="text-right taxtotal">5.00</th>
    </tr>
    <tr>
      <th colspan="6">Net Amount</th>
      <th class="text-right netamount">4.00</th>
    </tr>
    <tr>
      <th colspan="6">Grand Total</th>
      <th class="text-right grandtotal">6.00</th>
    </tr>
  </tbody>
</table>
<button id="save">Save</button>

【讨论】:

以上是关于如何使用 JQuery 从动态 html 表中获取选定的行值?的主要内容,如果未能解决你的问题,请参考以下文章

使用 c#、selenium 和 jquery 实现 IE 自动化 - 从动态表中随机获取

如何打开模态 jquery 并从表中获取单元格值?

如何在不使用按钮或 tbody 的情况下从动态生成的表中单击一行来获取 HTML 表中单元格的值

如何使用 jQuery 将 Kendo DropDownList 动态添加到 html5 表中

使用 Jquery 使用正则表达式从 HTML 表中获取所有数据

如何从使用 jquery 动态创建的视频标签中获取视频持续时间?