У меня есть таблица 1, она имеет некоторые следующие данные прямо сейчас, которые могут быть до 50-100 строк. Я хочу обобщить информацию, содержащуюся в ней, нажав кнопку "Сводка" и хочу показать ее в другой таблице, которая будет создана "на лету" в соответствии с обобщенной информацией. Но я не знаю, как это сделать.
Я просто хочу, чтобы, если код существует более одного раза, чем в выходной таблице, все его Sq-In должны быть добавлены. Как и в приведенной выше таблице, A1 повторяется три раза, поэтому все его SqIn добавляются, и он дает A1 81. В настоящий момент идентификатор текстового поля кода: # code_0, # code_1, # code_2 и т.д. где SqIn - # sqin_0, # sqin_1, # sqin_2 и так далее...
<table id="myTable">
<thead>
<tr>
<th>Codes</th>
<th>room</th>
<th>SqIn</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value="A1" /></td>
<td><input type="text" value="1" /></td>
<td><input type="text" value="25"/></td>
</tr>
<tr>
<td><input type="text" value="B1" /></td>
<td><input type="text" value="1"/></td>
<td><input type="text" value="25"/></td>
</tr>
<tr>
<td><input type="text" value="C1" /></td>
<td><input type="text" value="1"/></td>
<td><input type="text" value="25"/></td>
</tr>
<tr>
<td><input type="text" value="A1" /></td>
<td><input type="text" value="2"/></td>
<td><input type="text" value="25"/></td>
</tr>
<tr>
<td><input type="text" value="B1" /></td>
<td><input type="text" value="1"/></td>
<td><input type="text" value="25"/></td>
</tr>
<tr>
<td><input type="text" value="C1"/></td>
<td><input type="text" value="2"/></td>
<td><input type="text" value="25"/></td>
</tr>
</tbody>
</table>
<button id=summarise ">Summarise</button>
<table id="SummarizedTable">
//here the summary table should come.
</table>
JS
SqIn: +(element.childNodes[1].firstElementChild.value)
В непосредственной близости от формы кода psuedo, но он будет выглядеть следующим образом:
var myList = {};
$('input[id^="code"]').each(function(){ // Grab all input with ID begins with 'code'
var myID = $(this).attr("id"); // Get the actual ID
if( myList[myID] == '' ){
var value = 0;
$('input').find('[id=' + myID + ']').each(function(){
value += $(this).next().val(); // Get the all elements next to all 'id=myID'
});
myList[myID] = value; // Insert the total
}
});
for( var i in myList ){
var id = i;
var value = myList[i];
// Draw the summary <td> using the id and the value here
}
var cells = [];
cells.push({code: 'A1', SqIn: 25});
Array.prototype.reduce
для объединения и суммирования информации ячейки в массиве.tbody
из table
reduce
(3)Пример
CSS
table, th, td {
border: 1px solid black;
}
HTML
<table id="myTable">
<thead>
<tr>
<th>Codes</th>
<th>SqIn</th>
</tr>
</thead>
<tbody>
<tr>
<td>A1</td>
<td>25</td>
</tr>
<tr>
<td>B1</td>
<td>25</td>
</tr>
<tr>
<td>C1</td>
<td>25</td>
</tr>
<tr>
<td>A1</td>
<td>50</td>
</tr>
<tr>
<td>B1</td>
<td>50</td>
</tr>
<tr>
<td>C1</td>
<td>50</td>
</tr>
</tbody>
</table>
<button id="summarise">Summarise</button>
Javascript
function emptyNode(node) {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
}
function summariseTable(tableId) {
var tbody = document.getElementById(tableId).lastElementChild,
reduced = Array.prototype.map.call(tbody.getElementsByTagName('tr'), function (element) {
return {
code: element.firstElementChild.textContent,
SqIn: +(element.lastElementChild.textContent)
};
}).reduce(function (acc, rowData) {
if (!acc.hasOwnProperty(rowData.code)) {
acc[rowData.code] = rowData.SqIn;
} else {
acc[rowData.code] += rowData.SqIn;
}
return acc;
}, {});
emptyNode(tbody);
Object.keys(reduced).forEach(function (code) {
var row = document.createElement('tr'),
tdCode = document.createElement('td'),
tdSqIn = document.createElement('td');
tdCode.appendChild(document.createTextNode(code));
tdSqIn.appendChild(document.createTextNode(reduced[code]));
row.appendChild(tdCode);
row.appendChild(tdSqIn);
tbody.appendChild(row);
});
}
document.getElementById('summarise').addEventListener('click', function () {
summariseTable('myTable');
}, false);
На jsFiddle
Этот пример заменяет содержимое текущей таблицы, но вы можете легко создать вместо него новую таблицу. Если у вас есть input
в td
тогда получите value
для них.
input
:(
SqIn: +(element.lastElementChild.textContent)
-> SqIn: +(element.lastElementChild.firstElementChild.value)
return duplicates
:( Как вы думаете, это полезно в моем случае ????