merging <td> rows in one column of html table - javascript

I have a requirement, if i have same data in column1 of 's with same id then i need to merge those cells and show their respective values in column2.
i.e., in fiddle http://jsfiddle.net/7t9qkLc0/12/ the key column have 3rows with data 1 as row value with same id and has corresponding different values in Value column i.e., AA,BB,CC. I want to merge the 3 rows in key Column and display data 1 only once and show their corresponding values in separate rows in value column.
Similarly for data4 and data5 the values are same i.e.,FF and keys are different, i want to merge last 2 rows in Value column and dispaly FF only one time and show corresponding keys in key column. All data i'm getting would be the dynamic data. Please suggest.
Please find the fiddle http://jsfiddle.net/7t9qkLc0/12/
Sample html code:
<table width="300px" height="150px" border="1">
<tr><th>Key</th><th>Value</th></tr>
<tr>
<td id="1">data 1</td>
<td id="aa">AA</td>
</tr>
<tr>
<td id="1">data 1</td>
<td id="bb">BB</td>
</tr>
<tr>
<td id="1">data 1</td>
<td id="cc">CC</td>
</tr>
<tr>
<td id="2">data 2</td>
<td id="dd">DD</td>
</tr>
<tr>
<td id="2">data 2</td>
<td id="ee">EE</td>
</tr>
<tr>
<td id="3">data 3</td>
<td id="ff">FF</td>
</tr>
<tr>
<td id="4">data 4</td>
<td id="ff">FF</td>
</tr>
<tr>
<td id="5">data 5</td>
<td id="ff">FF</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="3" style="padding-left: 0px; padding-right: 0px; padding-bottom: 0px">
</td>
</tr>
</table>

Building on tkounenis' answer using Rowspan:
One option to implement what you need would be to read all the values in your table after being populated, then use a JS object literal as a data structure to figure out what rows/columns are unique.
A JS object literal requires a unique key which you can map values to. After figuring out what rows/columns should be grouped, you can either edit the original table, or hide the original table and create a new table (I'm creating new tables in this example).
I've created an example for you to create a new table either grouped by key or grouped by value. Try to edit the examples provided to introduce both requirements.
Let me know if you need more help. Best of luck.
JSFiddle: http://jsfiddle.net/biz79/x417905v/
JS (uses jQuery):
sortByCol(0);
sortByCol(1);
function sortByCol(keyCol) {
// keyCol = 0 for first col, 1 for 2nd col
var valCol = (keyCol === 0) ? 1 : 0;
var $rows = $('#presort tr');
var dict = {};
var col1name = $('th').eq(keyCol).html();
var col2name = $('th').eq(valCol).html();
for (var i = 0; i < $rows.length; i++) {
if ($rows.eq(i).children('td').length > 0) {
var key = $rows.eq(i).children('td').eq(keyCol).html();
var val = $rows.eq(i).children('td').eq(valCol).html();
if (key in dict) {
dict[key].push(val);
} else {
dict[key] = [val];
}
}
}
redrawTable(dict,col1name,col2name);
}
function redrawTable(dict,col1name,col2name) {
var $table = $('<table>').attr("border",1);
$table.css( {"width":"300px" } );
$table.append($('<tr><th>' +col1name+ '</th><th>' +col2name+ '</th>'));
for (var prop in dict) {
for (var i = 0, len = dict[prop].length; i< len; i++) {
var $row = $('<tr>');
if ( i == 0) {
$row.append( $("<td>").attr('rowspan',len).html( prop ) );
$row.append( $("<td>").html( dict[prop][i] ) );
}
else {
$row.append( $("<td>").html( dict[prop][i] ) );
}
$table.append($row);
}
}
$('div').after($table);
}

Use the rowspan attribute like so:
<table width="300px" height="150px" border="1">
<tr>
<th>Key</th>
<th>Value</th>
</tr>
<tr>
<td id="1" rowspan="3">data 1</td>
<td id="aa">AA</td>
</tr>
<tr>
<td id="bb">BB</td>
</tr>
<tr>
<td id="cc">CC</td>
</tr>
<tr>
<td id="2" rowspan="2">data 2</td>
<td id="dd">DD</td>
</tr>
<tr>
<td id="ee">EE</td>
</tr>
<tr>
<td id="3">data 3</td>
<td id="ff">FF</td>
</tr>
<tr>
<td id="4">data 4</td>
<td id="ff">FF</td>
</tr>
<tr>
<td id="5">data 5</td>
<td id="ff">FF</td>
</tr>
</table>

http://jsfiddle.net/37b793pz/4/
Can not be used more than once the same id. For that use data-id attribute
HTML:
<table width="300px" height="150px" border="1">
<tr>
<th>Key</th>
<th>Value</th>
</tr>
<tr>
<td data-id="key1">data 1</td>
<td data-id="valaa">AA</td>
</tr>
<tr>
<td data-id="key1">data 1</td>
<td data-id="valbb">BB</td>
</tr>
<tr>
<td data-id="key1">data 1</td>
<td data-id="valcc">CC</td>
</tr>
<tr>
<td data-id="key2">data 2</td>
<td data-id="valdd">DD</td>
</tr>
<tr>
<td data-id="key2">data 2</td>
<td data-id="valee">EE</td>
</tr>
<tr>
<td data-id="key3">data 3</td>
<td data-id="valff">FF</td>
</tr>
<tr>
<td data-id="key4">data 4</td>
<td data-id="valff">FF</td>
</tr>
<tr>
<td data-id="key5">data 5</td>
<td data-id="valff">FF</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="3" style="padding-left: 0px; padding-right: 0px; padding-bottom: 0px"></td>
</tr>
</table>
JQ:
//merge cells in key column
function mergerKey() {
// prevents the same attribute is used more than once Ip
var idA = [];
// finds all cells id column Key
$('td[data-id^="key"]').each(function () {
var id = $(this).attr('data-id');
// prevents the same attribute is used more than once IIp
if ($.inArray(id, idA) == -1) {
idA.push(id);
// finds all cells that have the same data-id attribute
var $td = $('td[data-id="' + id + '"]');
//counts the number of cells with the same data-id
var count = $td.size();
if (count > 1) {
//If there is more than one
//then merging
$td.not(":eq(0)").remove();
$td.attr('rowspan', count);
}
}
})
}
//similar logic as for mergerKey()
function mergerVal() {
var idA = [];
$('td[data-id^="val"]').each(function () {
var id = $(this).attr('data-id');
if ($.inArray(id, idA) == -1) {
idA.push(id);
var $td = $('td[data-id="' + id + '"]');
var count = $td.size();
if (count > 1) {
$td.not(":eq(0)").remove();
$td.attr('rowspan', count);
}
}
})
}
mergerKey();
mergerVal();

Use below snippet of javascript. It should work fine for what you are looking.
<script type="text/javascript">
function mergeCommonCells(table, columnIndexToMerge){
previous = null;
cellToExtend = null;
table.find("td:nth-child("+columnIndexToMerge+")").each(function(){
jthis = $(this);
content = jthis.text();
if(previous == content){
jthis.remove();
if(cellToExtend.attr("rowspan") == undefined){
cellToExtend.attr("rowspan", 2);
}
else{
currentrowspan = parseInt(cellToExtend.attr("rowspan"));
cellToExtend.attr("rowspan", currentrowspan+1);
}
}
else{
previous = content;
cellToExtend = jthis;
}
});
};
mergeCommonCells($("#tableId"), 1);
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

Related

If I apply the excel file to the html table, I want to give each td a different id

Sign up and first question. I keep looking to solve my problem but haven't found an answer yet. The question is, like the title, I want to load an excel file into an html table and give each td a different ID.
Currently, I have succeeded in assigning an id, but I know that the id value must not be the same. So I want to solve this problem with vanilla JavaScript. Below are the scripts I've completed so far and the results shown in the Chrome Developer Tools.
SCRIPT:
document.getElementById("ex_file").onchange = (evt) => {
var reader = new FileReader();
reader.addEventListener("loadend", (evt) => {
var table = document.getElementById("importexcel");
table.innerHTML = "";
var workbook = XLSX.read(evt.target.result, {type: "binary"}),
worksheet = workbook.Sheets[workbook.SheetNames[0]],
range = XLSX.utils.decode_range(worksheet["!ref"]);
for (let row=range.s.r; row<=range.e.r; row++) {
let r = table.insertRow();
for (let col=range.s.c; col<=range.e.c; col++) {
let c = r.insertCell(),
xcell = worksheet[XLSX.utils.encode_cell({r:row, c:col})];
c.innerHTML = xcell.v;
c.setAttribute('id', 'excel' + numbering)
var numbering = 0;
numbering++;
}
}
});
reader.readAsArrayBuffer(evt.target.files[0]);
};
Chrome Developer Tools:
<table id="importexcel" class="table">
<tbody>
<tr>
<td id="excelundefined">STYLE</td>
<td id="excel1">XS 90</td>
<td id="excel1">X 95</td>
<td id="excel1">M 100</td>
<td id="excel1">L 105</td>
<td id="excel1">XL 110</td>
<td id="excel1">XXL 115</td>
<td id="excel1">TOTAL</td>
</tr>
<tr>
<td id="excel1">hgfhgfhgf</td>
<td id="excel1">3</td>
<td id="excel1">4</td>
<td id="excel1">0</td>
<td id="excel1">4</td>
<td id="excel1">0</td>
<td id="excel1">4</td>
<td id="excel1">15</td>
</tr>
</tbody>
</table>
Below is the result I want:
<table id="importexcel" class="table">
<tbody>
<tr>
<td id="excelundefined">STYLE</td>
<td id="excel1">XS 90</td>
<td id="excel2">X 95</td>
<td id="excel3">M 100</td>
<td id="excel4">L 105</td>
<td id="excel5">XL 110</td>
<td id="excel6">XXL 115</td>
<td id="excel7">TOTAL</td>
</tr>
<tr>
<td id="excel8">hgfhgfhgf</td>
<td id="excel9">3</td>
<td id="excel10">4</td>
<td id="excel11">0</td>
<td id="excel12">4</td>
<td id="excel13">0</td>
<td id="excel14">4</td>
<td id="excel15">15</td>
</tr>
</tbody>
</table>
The script used another developer's script. If there is a problem, I would like to get help. Please feel free to comment if you need a little more information for an accurate answer!

jquery - show / hide elements rows by elemenst in data-id array

I have table with rows like that:
<tr class="listRow" data-id="[11,0]">...</tr>
<tr class="listRow" data-id="[1,2,3]">...</tr>
How i can using JQuery filter specific rows with element in array? For example by button click show all rows with 1 in array and hide rest.
Edit - my sample code so far:
i don't know how to filtering elements in data-id array.
$(document).on('click','#filterList',function()
{
var element = $(this).data("id");
// how to filter elements in rows
}
);
If i understand correctly:
$('#check').click(function() {
$('.listRow').each(function() {
if($.inArray(1, $(this).data().id)>-1) {
$(this).show();
}
else {
$(this).hide()
}
});
});
$('#check').click(function() {
$('.listRow').each(function() {
if($.inArray(1, $(this).data().id)>-1) {
$(this).show();
}
else {
$(this).hide()
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tg">
<thead>
<tr class="listRow" data-id="[1,0]">
<th class="tg-0pky">Here is 1</th>
<th class="tg-0pky">xxxx</th>
<th class="tg-0pky"></th>
<th class="tg-0pky"></th>
</tr>
</thead>
<tbody>
<tr class="listRow" data-id="[11,0]">
<td class="tg-0pky">Not 1</td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
</tr>
<tr class="listRow" data-id="[15,0]" >
<td class="tg-0pky">Not 1</td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
</tr>
<tr class="listRow" data-id="[1,0,3]">
<td class="tg-0pky" >Here is 1</td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
</tr>
</tbody>
</table>
<button id="check">
Click
</button>
when you press the button, loop through all the elements that have a data-id
parse the data-id as json, which will give you an array
if the array includes the id you're looking for, set the class to hide or show (where they have the display css assigned accordingly)
here's what that might look like without jquery and using style and opacity. Usually it's done using class but this is for demonstration purposes, changing to use classes should be straight forward.
function findElsById(id){
var matches = []
document.querySelectorAll('[data-id]').forEach(function(el){
try{
var arr = JSON.parse(el.dataset.id)
if (arr.includes(id)) matches.push(el)
} catch (e){
// prolly not valid json
}
})
return matches
}
function show(id){
var els = findElsById(id);
console.log('show', id, '\nshowing: ', els)
if (els) {
els.forEach(function(el){
el.style = 'opacity:1'
})
}
}
function hide(id){
var els = findElsById(id);
console.log('hide', id, '\nhiding: ', els)
if (els) {
els.forEach(function(el){
el.style = 'opacity:0.1'
})
}
}
<table>
<tr class="listRow" data-id="[1,0]"><td>1, 0</td></tr>
<tr class="listRow" data-id="[1,2]"><td>1, 2</td></tr>
</table>
<button onclick="hide(0)">-0</button>
<button onclick="hide(1)">-1</button>
<button onclick="hide(2)">-2</button>
<button onclick="show(0)">+0</button>
<button onclick="show(1)">+1</button>
<button onclick="show(2)">+2</button>

Function name is not defined at HTMLTableCellElement.onclick

I want to make X and O game , So the first function i did it has loop and condition that when i click on any cell(td) in the table and if all cells in the table are empty wrote X in the cell which I clicked it , but I have here 2 problem ,
First one The console wrote (Sample1.html:53 Uncaught SyntaxError: Unexpected token '<') it refers to for loop, so I don't know what is the problem there.
the second problem console wrote also that my function name is not define , although the function name is correct so can anyone help me.
the JS codes is
<script >
/*var lastGame;*/
var TR=0;
var table = document.getElementById('tb');
function CheckAllEmpty(idClicked){
for(var x=0, x < table.rows.length; x++){
if(!table.rows[x])
{
TR++;
}
else{}
}
if(TR==9)
{
document.getElementById(idClicked).innerHTML="X";
}
else {}
}
</script>
And the HTML :
<table id="tb">
<tr>
<td id="td1" onclick="CheckAllEmpty(this.id);"></td>
<td id="td2"></td>
<td id="td3"></td>
</tr>
<tr>
<td id="td4"></td>
<td id="td5"></td>
<td id="td6"></td>
</tr>
<tr>
<td id="td7"></td>
<td id="td8"></td>
<td id="td9"></td>
</tr>
</table>
There seems to be other problems with your code, but your two specific problems should be fixed. Also I don't see why you need to check if every cell is empty, but then again I can't see the rest of your code. Feel free to ask any questions in the comments.
var TR = 0;
var table = document.getElementById('tb');
function CheckAllEmpty(idClicked) {
for (var x = 0; x < table.rows.length; x++) {
if (!(table.rows[x].value == "")) {
TR++;
console.log(TR);
}
}
if (TR == 3) {
document.getElementById(idClicked).innerHTML = "X";
}
}
CheckAllEmpty('td1');
<table id="tb">
<tr>
<td id="td1" onclick="CheckAllEmpty(this.id)"></td>
<td id="td2"></td>
<td id="td3"></td>
</tr>
<tr>
<td id="td4"></td>
<td id="td5"></td>
<td id="td6"></td>
</tr>
<tr>
<td id="td7"></td>
<td id="td8"></td>
<td id="td9"></td>
</tr>
</table>

Sorting pairs of rows with tablesorter

http://jsfiddle.net/9sKwJ/66/
tr.spacer { height: 40px; }
$.tablesorter.addWidget({
id: 'spacer',
format: function(table) {
var c = table.config,
$t = $(table),
$r = $t.find('tbody').find('tr'),
i, l, last, col, rows, spacers = [];
if (c.sortList && c.sortList[0]) {
$t.find('tr.spacer').removeClass('spacer');
col = c.sortList[0][0]; // first sorted column
rows = table.config.cache.normalized;
last = rows[0][col]; // text from first row
l = rows.length;
for (i=0; i < l; i++) {
// if text from row doesn't match last row,
// save it to add a spacer
if (rows[i][col] !== last) {
spacers.push(i-1);
last = rows[i][col];
}
}
// add spacer class to the appropriate rows
for (i=0; i<spacers.length; i++){
$r.eq(spacers[i]).addClass('spacer');
}
}
}
});
$('table').tablesorter({
widgets : ['spacer']
});
<table id="test">
<thead>
<tr>
<th>Name</th>
<th>Number</th>
<th>Another Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>Test4</td>
<td>4</td>
<td>Hello4</td>
</tr>
<tr>
<td colspan="3">Test4</td>
</tr>
<tr>
<td>Test3</td>
<td>3</td>
<td>Hello3</td>
</tr>
<tr>
<td colspan="3">Test3</td>
</tr>
<tr>
<td>Test2</td>
<td>2</td>
<td>Hello2</td>
</tr>
<tr>
<td colspan="3">Test2</td>
</tr>
<tr>
<td>Test1</td>
<td>1</td>
<td>Hello1</td>
</tr>
<tr>
<td colspan="3">Test1</td>
</tr>
</tbody>
</table>
This sorts just the way I want it if you sort it by the first column, but the other two columns don't maintain the same paired 'tr' sort im looking for.
Any help on this?
Use the expand-child class name on each duplicated row:
<tr>
<td>Test3</td>
<td>3</td>
<td>Hello3</td>
</tr>
<tr class="expand-child">
<td colspan="3">Test3</td>
</tr>
It's defined by the cssChildRow option:
$('table').tablesorter({
cssChildRow: "expand-child"
});​
Here is a demo of it in action.

Sum total for column in jQuery

The following code isn't working. I need to sum all by column as you can see on jsfiddle. What's going wrong?
HTML
<table id="sum_table" width="300" border="1">
<tr>
<td>Apple</td>
<td>Orange</td>
<td>Watermelon</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr class="totalColumn">
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
</tr>
</table>
Javascript
$(document).ready(function(){
$(".rowDataSd").each(function() {
newSum.call(this);
});
});
function newSum() {
var $table = $(this).closest('table');
var total = 0;
$(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.totalColumn) .rowDataSd').each(function() {
total += parseInt($(this).html());
});
$table.find('.totalColumn td:nth-child('')').html(total);
}
Here is a jsffile. hope this helps
<table id="sum_table" width="300" border="1">
<tr class="titlerow">
<td>Apple</td>
<td>Orange</td>
<td>Watermelon</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">5</td>
<td class="rowDataSd">3</td>
</tr>
<tr class="totalColumn">
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
</tr>
</table>
<script>
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.rowDataSd').each(function(i){
totals[i]+=parseInt( $(this).html());
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html("total:"+totals[i]);
});
});
</script>
jsFiddle with example
To achieve this, we can take full advantage of the thead and tfoot tags within the table element. With minor changes, we have the following:
HTML
<table id="sum_table" width="300" border="1">
<thead>
<tr>
<th>Apple</th>
<th>Orange</th>
<th>Watermelon</th>
</tr>
</thead>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tfoot>
<tr>
<td>Total:</td>
<td>Total:</td>
<td>Total:</td>
</tr>
</tfoot>
</table>​​​​​​​​​​​​​​​
This then allows us to target more specifically the elements we want, i.e. how many columns are there, and what is the "total" cell.
JavaScript
$(document).ready(function()
{
$('table thead th').each(function(i)
{
calculateColumn(i);
});
});
function calculateColumn(index)
{
var total = 0;
$('table tr').each(function()
{
var value = parseInt($('td', this).eq(index).text());
if (!isNaN(value))
{
total += value;
}
});
$('table tfoot td').eq(index).text('Total: ' + total);
}​
$('#sum_table tr:first td').each(function(){
var $td = $(this);
var colTotal = 0;
$('#sum_table tr:not(:first,.totalColumn)').each(function(){
colTotal += parseInt($(this).children().eq($td.index()).html(),10);
});
$('#sum_table tr.totalColumn').children().eq($td.index()).html('Total: ' + colTotal);
});
Live example: http://jsfiddle.net/unKDk/7/
An alternate way:
$(document).ready(function(){
for (i=0;i<$('#sum_table tr:eq(0) td').length;i++) {
var total = 0;
$('td.rowDataSd:eq(' + i + ')', 'tr').each(function(i) {
total = total + parseInt($(this).text());
});
$('#sum_table tr:last td').eq(i).text(total);
}
});
Example: http://jsfiddle.net/lucuma/unKDk/10/
This is easily accomplished with a little tweaking of the classes on your table:
HTML:
<table id="sum_table" width="300" border="1">
<tr>
<td>Apple</td>
<td>Orange</td>
<td>Watermelon</td>
</tr>
<tr>
<td class="col1">1</td>
<td class="col2">2</td>
<td class="col3">3</td>
</tr>
<tr>
<td class="col1">1</td>
<td class="col2">2</td>
<td class="col3">3</td>
</tr>
<tr>
<td class="col1">1</td>
<td class="col2">2</td>
<td class="col3">3</td>
</tr>
<tr>
<td class="total">Total:</td>
<td class="total">Total:</td>
<td class="total">Total:</td>
</tr>
</table>​
JS:
var getSum = function (colNumber) {
var sum = 0;
var selector = '.col' + colNumber;
$('#sum_table').find(selector).each(function (index, element) {
sum += parseInt($(element).text());
});
return sum;
};
$('#sum_table').find('.total').each(function (index, element) {
$(this).text('Total: ' + getSum(index + 1));
});
http://jsfiddle.net/unKDk/9/
I know this has been well answered by now, but I started working on this solution earlier before all the answers came through and wanted to go ahead and post it.
This solution works with the HTML as you posted it, and assumes 4 things: 1) the first row is the header row, 2) the last row is the totals row, 3) each row has equal columns, and 4) the columns contain integers. In this case, only the table needs to be identified.
$(document).ready(function(){
totalRows("#sum_table");
});
function totalRows(tableSelector) {
var table = $(tableSelector);
var rows = table.find("tr");
var val, totals = [];
//loop through the rows getting values in the rowDataSd columns
rows
.each(function(rIndex) {
if (rIndex > 0 && rIndex < (rows.length-1)) { //not first or last row
//loop through the columns
$(this).find("td").each(function(cIndex) {
val = parseInt($(this).html());
(totals.length>cIndex) ? totals[cIndex]+=val : totals.push(val);
});
}
})
.last().find("td").each(function(index) {
val = (totals.length>index) ? totals[index] : 0;
$(this).html( "Total: " + val );
});
}
​
​
Here you go sir! http://jsfiddle.net/47VDK/

Categories

Resources