我正在使用資料表并為一列使用文本框
render: function (data, type, row) {
return '<input id="itemId" name="itemId" maxlength="350" multiline="true" type="text" >';
對于這個特定的列,用戶將手動輸入資料,我如何對所有這些文本框進行求和。
uj5u.com熱心網友回復:
您可以使用 DataTables API 訪問<td>相關列中的每個節點。從那里您可以訪問為每個<input>欄位設定的值,然后對這些值求和。
通過使用 DataTables API 來執行此操作,您將確保對所有單元格進行求和,即使是未顯示在當前頁面中的單元格也是如此。
這是一個演示:
var dataSet = [
{
"id": "1",
"amount": 1
},
{
"id": "2",
"amount": 3
},
{
"id": "3",
"amount": 5
},
{
"id": "4",
"amount": 2
},
{
"id": "5",
"amount": 3
},
{
"id": "6",
"amount": 1
},
{
"id": "7",
"amount": 4
},
{
"id": "8",
"amount": 3
},
{
"id": "9",
"amount": 1
},
{
"id": "10",
"amount": 2
},
{
"id": "11",
"amount": 2
},
{
"id": "12",
"amount": 3
},
{
"id": "13",
"amount": 1
},
{
"id": "14",
"amount": 1
}
];
$(document).ready(function() {
var table = $('#example').DataTable( {
data: dataSet,
columns: [
{ title: "ID", data: "id" },
{ title: "Amount", data: "amount",
render: function (data, type, row) {
return '<input type="number" value="' data '">';
}
}
],
initComplete: function(settings, json) {
doSum();
}
} );
// This provides the sum of all "approved" records:
function doSum() {
// get the DataTables API object:
var table = $('#example').DataTable();
// access the <td> cell nodes for the relevant column:
var nodes = table.column( 1 ).nodes();
// get the value from each input field in each cell:
var total = table.column( 1 ).nodes()
// and then sum up the integer values:
.reduce( function ( sum, node ) {
return sum parseInt($( node ).find( 'input' ).val());
}, 0 );
// place the sum in the relevant footer cell:
$( table.column( 1 ).footer() ).html( total );
}
// ensure all changes made by the user are reflected in the
// total field:
$('#example').on( 'change', 'input', function () {
doSum();
} );
} );
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display dataTable cell-border" style="width:100%">
<tfoot>
<th style="text-align: right;">Total:</th><th></th>
</tfoot>
</table>
</div>
</body>
</html>
上面的演示假設您在欄位中有起始值。當然,如果它們與您的場景不相關,您可以洗掉它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/314698.html
標籤:javascript 查询 阿贾克斯 数据表 数据表
上一篇:選擇器似乎沒有回傳的選項
