Sorting HTML table with subitems with JS - javascript

I have the following table:
<table border="0" cellspacing="0" cellpadding="0" id="table1">
<tbody>
<tr>
<th onclick="sortTable(0, this); return false;" class="sort-up" order="-1">ColumnA</th>
<th style="width: 12em;" onclick="sortTable(1, this); return false;" class="sort-none">ColumnB</th>
<th style="width: 9em;" onclick="sortTable(2, this); return false;" class="sort-none">ColumnC</th>
<th style="width: 10em;" onclick="sortTable(3, this); return false;" class="sort-none">ColumnD</th>
<th style="width: 6em;">ColumnE</th>
</tr>
<tr id="tr217E9B6C" type="root" level="217E9B6C" depth="0">
<td class="evenListRow" id="nocenter">
<div class="tier1">Root A</div>
</td>
<td class="evenListRow">1</td>
<td class="evenListRow">2</td>
<td class="evenListRow">3</td>
<td class="evenListRow">4</a>
</td>
</tr>
<tr id="tr217E9B6C-6E781501" type="sub" level="217E9B6C-6E781501" depth="1">
<td class="oddListRow" id="nocenter">
<div class="tier2">Sub A</div>
</td>
<td class="oddListRow">5</td>
<td class="oddListRow">6</td>
<td class="oddListRow">7</td>
<td class="oddListRow">8</td>
</tr>
<tr id="tr217E9B6C-852AB6E5" type="sub" level="217E9B6C-852AB6E5" depth="1">
<td class="evenListRow" id="nocenter">
<div class="tier2">Sub B</div>
</td>
<td class="evenListRow">9</td>
<td class="evenListRow">10</td>
<td class="evenListRow">11</td>
<td class="evenListRow">12</td>
</tr>
<tr id="tr2BE7EAFE" type="root" level="2BE7EAFE" depth="0">
<td class="evenListRow" id="nocenter">
<div class="tier1">Root B</div>
</td>
<td class="evenListRow">13</td>
<td class="evenListRow">14</td>
<td class="evenListRow">15</td>
<td class="evenListRow">16</td>
</tr>
<tr id="tr2BE7EAFE-49A04568" type="sub" level="2BE7EAFE-49A04568" depth="1">
<td class="oddListRow" id="nocenter">
<div class="tier2">Sub C</div>
</td>
<td class="oddListRow">17</td>
<td class="oddListRow">18</td>
<td class="oddListRow">19</td>
<td class="oddListRow">20</td>
</tr>
<tr id="tr2BE7EAFE-DAE218A5" type="sub" level="2BE7EAFE-DAE218A5" depth="1">
<td class="evenListRow" id="nocenter">
<div class="tier2">Sub D</div>
</td>
<td class="evenListRow">21</td>
<td class="evenListRow">22</td>
<td class="evenListRow">23</td>
<td class="evenListRow">24</td>
</tr>
<tr id="tr4FFACE4A" type="root" level="4FFACE4A" depth="0">
<td class="oddListRow" id="nocenter">
<div class="tier1">Root C</div>
</td>
<td class="oddListRow">25</td>
<td class="oddListRow">26</td>
<td class="oddListRow">27</td>
<td class="oddListRow">28</td>
</tr>
<tr id="tr4FFACE4A-B9A443CA" type="sub" level="4FFACE4A-B9A443CA" depth="1">
<td class="evenListRow" id="nocenter">
<div class="tier2">Sub E</div>
</td>
<td class="evenListRow">29</td>
<td class="evenListRow">30</td>
<td class="evenListRow">31</td>
<td class="evenListRow">32</td>
</tr>
</tbody>
</table>
And I want to sort it, first by the "root" then by the "sub" items, which would mean that Root A will always have its Sub A, Sub B under it (sorted as well, but under it)
I used the following code which works on only on the "sub items", I cannot get it to work by doing a "mix", i.e. top and sub (separately sorted)
function sortTable(column, thisrow) {
var order = thisrow.getAttribute('order');
if (!order) {
order = 1;
}
var tbl = document.getElementById("table1").tBodies[0];
if (!tbl) {
return;
}
if (previousSortColumn && previousSortColumn.innerHTML != thisrow.innerHTML) {
previousSortColumn.setAttribute('class', 'sort-none');
}
previousSortColumn = thisrow;
var store = [];
/* Build a store object that has every element in the table, we will use this to sort */
for(var rowpos=1, len=tbl.rows.length; rowpos<len; rowpos++) { // skip row #1 as it is the header
var row = tbl.rows[rowpos];
var i_textContent = row.cells[column].textContent;
while(i_textContent.indexOf(' ') != -1) { // remove spaces
i_textContent = i_textContent.replace(' ', '');
}
var sortnr = i_textContent;
var type = row.getAttribute('type');
var level = row.getAttribute('level');
var depth = row.getAttribute('depth');
store.push({sortnr: sortnr, row:row, storelength:store.length, type:type, level:level, depth:depth});
}
/* We sort first roots then the elements under it */
store.sort(function(x,y) {
var xtype = x['type'];
var ytype = y['type'];
var result;
if (xtype == 'root' && ytype == 'root')
{
result = x['sortnr'].localeCompare(y['sortnr']);
} else {
return 0;
}
if (order == 1) {
return result;
} else {
return -1 * result;
}
});
/* We sort the elements under it */
store.sort(function(x,y) {
var xtype = x['type'];
var ytype = y['type'];
var xlevel = x['level'];
var ylevel = y['level'];
if (xlevel.lastIndexOf('-') > 0) {
xlevel = xlevel.substring(0, xlevel.lastIndexOf('-'));
}
if (ylevel.lastIndexOf('-') > 0) {
ylevel = ylevel.substring(0, ylevel.lastIndexOf('-'));
}
if (xlevel != ylevel || xtype == 'root' || ytype == 'root')
{
return x['storelength'] - y['storelength']; // return order inside array
}
var result = x['sortnr'].localeCompare(y['sortnr']);
if (order == 1) {
return result;
} else {
return -1 * result;
}
});
for(var i=0; i < store.length; i++) {
tbl.appendChild(store[i]['row']);
}
store = null;
}
Update 1:
Clicking once on 'ColumnB' would not affect the table (a bit of a bad example on my part), as the information is already sorted in the correct order, however another click should sort everything in reverse order
So both the Roots would be in reverse other, Root C, Root B, Root A, as well their sub items, Sub D before Sub C, ...
<table border="0" cellspacing="0" cellpadding="0" id="table1">
<tbody>
<tr>
<th onclick="sortTable(0, this); return false;" class="sort-up" order="-1">ColumnA</th>
<th style="width: 12em;" onclick="sortTable(1, this); return false;" class="sort-none">ColumnB</th>
<th style="width: 9em;" onclick="sortTable(2, this); return false;" class="sort-none">ColumnC</th>
<th style="width: 10em;" onclick="sortTable(3, this); return false;" class="sort-none">ColumnD</th>
<th style="width: 6em;">ColumnE</th>
</tr>
<tr id="tr4FFACE4A" type="root" level="4FFACE4A" depth="0">
<td class="oddListRow" id="nocenter">
<div class="tier1">Root C</div>
</td>
<td class="oddListRow">25</td>
<td class="oddListRow">26</td>
<td class="oddListRow">27</td>
<td class="oddListRow">28</td>
</tr>
<tr id="tr4FFACE4A-B9A443CA" type="sub" level="4FFACE4A-B9A443CA" depth="1">
<td class="evenListRow" id="nocenter">
<div class="tier2">Sub E</div>
</td>
<td class="evenListRow">29</td>
<td class="evenListRow">30</td>
<td class="evenListRow">31</td>
<td class="evenListRow">32</td>
</tr>
<tr id="tr2BE7EAFE" type="root" level="2BE7EAFE" depth="0">
<td class="evenListRow" id="nocenter">
<div class="tier1">Root B</div>
</td>
<td class="evenListRow">13</td>
<td class="evenListRow">14</td>
<td class="evenListRow">15</td>
<td class="evenListRow">16</td>
</tr>
<tr id="tr2BE7EAFE-DAE218A5" type="sub" level="2BE7EAFE-DAE218A5" depth="1">
<td class="evenListRow" id="nocenter">
<div class="tier2">Sub D</div>
</td>
<td class="evenListRow">21</td>
<td class="evenListRow">22</td>
<td class="evenListRow">23</td>
<td class="evenListRow">24</td>
</tr>
<tr id="tr2BE7EAFE-49A04568" type="sub" level="2BE7EAFE-49A04568" depth="1">
<td class="oddListRow" id="nocenter">
<div class="tier2">Sub C</div>
</td>
<td class="oddListRow">17</td>
<td class="oddListRow">18</td>
<td class="oddListRow">19</td>
<td class="oddListRow">20</td>
</tr>
<tr id="tr217E9B6C" type="root" level="217E9B6C" depth="0">
<td class="evenListRow" id="nocenter">
<div class="tier1">Root A</div>
</td>
<td class="evenListRow">1</td>
<td class="evenListRow">2</td>
<td class="evenListRow">3</td>
<td class="evenListRow">4</a>
</td>
</tr>
<tr id="tr217E9B6C-852AB6E5" type="sub" level="217E9B6C-852AB6E5" depth="1">
<td class="evenListRow" id="nocenter">
<div class="tier2">Sub B</div>
</td>
<td class="evenListRow">9</td>
<td class="evenListRow">10</td>
<td class="evenListRow">11</td>
<td class="evenListRow">12</td>
</tr>
<tr id="tr217E9B6C-6E781501" type="sub" level="217E9B6C-6E781501" depth="1">
<td class="oddListRow" id="nocenter">
<div class="tier2">Sub A</div>
</td>
<td class="oddListRow">5</td>
<td class="oddListRow">6</td>
<td class="oddListRow">7</td>
<td class="oddListRow">8</td>
</tr>
</tbody>
</table>

I solved your problem. I did reorganize the code to make it a lot more readable. Most of the logic is what you provided, i just added small bits. And btw, you have duplicate id references on id="nocenter" in your html.
Here is a working jsfiddle of my solution. The HTML is exactly the one you provided , with errors and all and no listener on column E. This js fiddle version has some more subs on root A. You can play with it as you will (add extra data). Summary of the code comes after it in the answer.
Update - taken your new input data in the comments , i updated the jsfiddle it would seem i kept the root in place, and it jumped out of subset. It was a matter of changing 1 line in sorting the subs. The new fiddle.
var ASC = 1;
var DESC = -1;
var SORTNR_INDEX = 0;
var LOWER = 1;
var UPPER = 2;
var previousSortColumn ;
var order;
/* The original build store you provided */
var buildStore = function(column,tbl){
var store = [];
for (var rowpos = 1, len = tbl.rows.length; rowpos < len; rowpos++) { // skip row #1 as it is the header
var row = tbl.rows[rowpos];
var i_textContent = row.cells[column].textContent;
while (i_textContent.indexOf(' ') != -1) { // remove spaces
i_textContent = i_textContent.replace(' ', '');
}
var sortnr = i_textContent;
var type = row.getAttribute('type');
var level = row.getAttribute('level');
var depth = row.getAttribute('depth');
store.push({sortnr: sortnr, row: row, storelength: store.length, type: type, level: level, depth: depth});
}
return store;
}
// the order convention you offered
var triggerOrder = function(){
if (order==ASC){
order = DESC;
} else if (order==DESC || !order){
order = ASC;
}
}
// the code you provided
var getLevel = function(obj){
if (obj && obj.lastIndexOf('-') > 0) {
return obj.substring(0, obj.lastIndexOf('-'));
}
return obj;
}
function sortRoot(a,b){
var aSort = a[SORTNR_INDEX], bSort = b[SORTNR_INDEX];
return compareWithOrder(aSort,bSort);
};
var sortSubs = function(x,y){
var xtype = x['type'];
var ytype = y['type'];
if (xtype == 'root'){
return -1;
} else if (xtype == ytype) {
var xSort = x['sortnr'];
var ySort = y['sortnr'];
return compareWithOrder(xSort,ySort);
}
}
var compareWithOrder = function(x,y){
if (isNaN(parseInt(x))) {
return order * x.localeCompare(y);
} else {
x = parseInt(x);
y = parseInt(y);
if (x < y) {
return -1 * order;
} else if (x > y) {
return 1 * order;
} else {
return 0;
}
}
};
//assumes they are aligned by depth (i.e. will always have a root then subs). if not, an additional sort can be made beforehand
function getGroupsByLevel(store){
var group = [];
var groupIndex=0;
var lower =0, upper, sortNo;
if (store.length > 0) {
var x,y;
for (var i = 0; i < store.length; i++) {
x = store[i];
if (store[i+1]){
y = store[i+1]
} else{
y = {};
}
var xtype = x['type'];
var ytype = y['type'];
if (xtype=='root'){
sortNo = x['sortnr'];
}
var xlevel = getLevel(x['level']);
var ylevel = getLevel(y['level']);
if (xlevel != ylevel){
group[groupIndex] = [sortNo,lower,i];
lower=i+1;
groupIndex++;
}
}
}
return group;
};
function sortTable(column, thisrow) {
order = thisrow.getAttribute('order');
triggerOrder();
thisrow.setAttribute('order',order);
var tbl = document.getElementById("table1").tBodies[0];
if (!tbl) return;
/* Build a store object that has every element in the table, we will use this to sort */
var store = buildStore(column,tbl);
var groups = getGroupsByLevel(store);
groups.sort(sortRoot);
var newStore=[];
for (var i=0;i<groups.length;i++){
var group = groups[i];
var rootAndSubs = store.slice(group[LOWER],group[UPPER]+1);
rootAndSubs.sort(sortSubs);
newStore=newStore.concat(rootAndSubs);
}
//update table
for (var i = 0; i < newStore.length; i++) {
tbl.appendChild(newStore[i]['row']);
}
store = null;
order = null;
}
Basically it goes like this:
set +trigger the order
build the store just like you intended
get groups of roots and their subs
sort the groups and then sort the each of the subs for the group
update the view
This is the first approach i thought of.

Related

Return the total based on a checkbox change

I have a table:
<table style="width:100%;">
<tr>
<td align="right" class="mainText"><div id="text-subtotal">Sub-Total:</div></td>
<td align="right" class="mainText"><div id="value-subtotal">103.75</div></td>
</tr>
<tr>
<td align="right" class="mainText"><div id="text-redemptions">Points Redeemed:</div></td>
<td align="right" class="mainText"><div id="value-redemptions">10.00</div></td>
</tr>
<tr>
<td align="right" class="mainText"><div id="text-tax">Sales Tax (Springside) :</div></td>
<td align="right" class="mainText"><div id="value-tax">5.59</div></td>
</tr>
<tr>
<td align="right" class="mainText"><div id="text-shipping">Shipping : </div></td>
<td align="right" class="mainText"><div id="value-shipping">0.00</div></td>
</tr>
<tr>
<td align="right" class="mainText"><div id="text-total">Total:</div></td>
<td align="right" class="mainText"><div id="value-total">99.34</div></td>
</tr>
</table>
I am looking to add in the value-redemptions value to the total or remove it based on a check box click.
I have the checkbox doing what I want, but I keep getting a NaN return on the total.
the javascript I am using is:
function myPoints() {
// Get the checkbox
var checkBox = document.getElementById("points");
var redemptions_text = document.getElementById("text-redemptions");
var redemptions_value = document.getElementById("value-redemptions");
var redemptions_notice = document.getElementById("point-notice");
var shipping = parseFloat(document.getElementById('value-shipping'));
var subtotal = parseFloat(document.getElementById('value-subtotal'));
var redemptions = parseFloat(document.getElementById('value-redemptions'));
var taxes = parseFloat(document.getElementById('value-tax'));
var total = subtotal + taxes + shipping - redemptions;
// If the checkbox is checked, display the output text
if (checkBox.checked == true){
redemptions_text.style.display = "block";
redemptions_value.style.display = "block";
redemptions_notice.style.display = "block";
document.getElementById('value-total').innerHTML = total;
} else {
redemptions = 0;
redemptions_text.style.display = "none";
redemptions_value.style.display = "none";
redemptions_notice.style.display = "none";
document.getElementById('value-total' ).innerHTML = total;
}
};
You are retrieving elements, rather than the text they contain. So, for example, rather than var shipping = parseFloat(document.getElementById('value-shipping'));, try var shipping = parseFloat(document.getElementById('value-shipping').innerText);

How to create a searchbar with JavaScript

Hello Im trying to create a searchbar for my table with javascript and works but with some issues. The problem is when I try to search in two rows. For example if I only search in Name works! but if I search Name and Last Name doesn't work.
Here is my js function
var textbuscar = document.getElementById("buscar");
textbuscar.onkeyup = function() {
buscar(this);
}
function buscar(inputbuscar) {
var valorabuscar = (inputbuscar.value).toLowerCase().trim();
var tabla_tr = document.getElementById("tabla").getElementsByTagName("tbody")[0].rows;
for (var i = 0; i < tabla_tr.length; i++) {
var tr = tabla_tr[i];
var textotr = (tr.innerText).toLowerCase();
tr.className = (textotr.indexOf(valorabuscar) >= 0) ? "mostrar" : "ocultar";
}
}
Here is a runnable copy:
var textbuscar = document.getElementById("buscar");
textbuscar.onkeyup = function(){
buscar(this);
}
function buscar(inputbuscar){
var valorabuscar = (inputbuscar.value).toLowerCase().trim();
var tabla_tr = document.getElementById("tabla").getElementsByTagName("tbody")[0].rows;
for(var i=0; i<tabla_tr.length; i++){
var tr = tabla_tr[i];
var textotr = (tr.innerText).toLowerCase();
tr.className = (textotr.indexOf(valorabuscar)>=0)?"mostrar":"ocultar";
}
}
.mostar{display:block;}
.ocultar{display:none;}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<linl rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
<h1 class="page-header">
My Table
</h1>
<!-- TABLA INICIA -->
<table id="tabla" class="table table-striped">
<thead>
<tr>
<th style="width:160px">Nombre</th>
<th>Apellido</th>
<th style="width:220px">Profesion</th>
<th style="width:140px">Sueldo</th>
</tr>
<tr>
<td colspan="4">
<input id="buscar" type="text" class="form-control" placeholder="Escriba algo para filtrar" />
</td>
</tr>
</thead>
<tbody>
<tr>
<td>Juan</td>
<td>Perez Patiño</td>
<td>Marketing Empresarial</td>
<td class="text-right">S/. 9000.00</td>
</tr>
<tr>
<td>Alberto</td>
<td>Gonzales Flores</td>
<td>Derecho</td>
<td class="text-right">S/. 4000.00</td>
</tr>
<tr>
<td>Gustavo</td>
<td>Bueno Bravo</td>
<td>Derecho</td>
<td class="text-right">S/. 7000.00</td>
</tr>
<tr>
<td>Enrique</td>
<td>Pacheco Perez</td>
<td>Derecho</td>
<td class="text-right">S/. 12000.00</td>
</tr>
<tr>
<td>Jaime</td>
<td>Andrade Gonzales</td>
<td>Economia</td>
<td class="text-right">S/. 7500.00</td>
</tr>
<tr>
<td>Andrea</td>
<td>Loayza Perez</td>
<td>Medicina Humana</td>
<td class="text-right">S/. 7500.00</td>
</tr>
<tr>
<td>Elvira</td>
<td>Gonzales Perez</td>
<td>Ingeniería de Sistema</td>
<td class="text-right">S/. 7500.00</td>
</tr>
<tr>
<td>Joseph</td>
<td>Rodriguez Pacheco</td>
<td>Ingeniería de Software</td>
<td class="text-right">S/. 8200.00</td>
</tr>
<tr>
<td>Pedro</td>
<td>kuczynski</td>
<td>Economista</td>
<td class="text-right">S/. 250000.00</td>
</tr>
<tr>
<td>Alan</td>
<td>García Perez</td>
<td>Derecho</td>
<td class="text-right">S/. 120000.00</td>
</tr>
<tr>
<td>Jose</td>
<td>Villanueva Salvador</td>
<td>Medicina Humana</td>
<td class="text-right">S/. 2900.00</td>
</tr>
<tr>
<td>Alberto</td>
<td>Lozano García</td>
<td>Medicina Humana</td>
<td class="text-right">S/. 2900.00</td>
</tr>
</tbody>
</table>
<!-- TABLA FINALIZA -->
</div>
</div>
</div>
A demo at jsFiddle to play with.
To give you a headstart, I modified your function a little bit. This still doesn't work the way you want, but it should guide you with an idea:
function buscar(inputbuscar){
var valorabuscar = (inputbuscar.value).toLowerCase().trim();
var arraydevalores = valorabuscar.split(" ");
console.log(arraydevalores); //CHECK WHAT THIS LOGS
var tabla_tr = document.getElementById("tabla").getElementsByTagName("tbody")[0].rows;
console.log(findOne(arraydevalores, tabla_tr));
for(var i=0; i<tabla_tr.length; i++){
var tr = tabla_tr[i];
var textotr = (tr.innerText).toLowerCase();
tr.className = (textotr.indexOf(valorabuscar)>=0)?"mostrar":"ocultar";
}
}
I split your valorabuscar variable where any spaces are, so now you have an array of the terms that the user is searching for sepparately in an array that looks like this:
["juan", "pérez", "patiño"]
This array is easier to manipulate so as to compare it with your table and return whatever's more similar to it. Good luck!
PS: Here's an appropriate question to help you continue: Check if an array contains any element of another array in JavaScript

JQuery/JavaScript - Perform calculations on 2 cells in each row and return results to 3rd cell in each row

I am attempting to do some calculations on two cells in each row (each has a unique class) and return the results to a third cell (has its own class as well). I have put each class into its own array and I am able to access the elements within. I am not entirely sure I am evening approaching this the right way, any help would be much appreciated. The math is (sub1 - sub2) / sub2
Here is my JSFiddle and here is my html for my table:
var sub1 = [];
var sub2 = [];
var sub3 = [];
$(function subP() {
$('.sub1').each(function(i, e) {
sub1.push($(e).text());
});
$('.sub2').each(function(i, e) {
sub2.push($(e).text());
});
$('.sub3').each(function(i, e) {
sub3.push($(e).text());
});
var x = (sub1[0] - sub2[0]) / sub2[0];
$('.sub3:first').html(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<th>test0</th>
<th>test1</th>
<th>test2</th>
<tr>
<td class="sub1">1</td>
<td class="sub2">2</td>
<td class="sub3">0</td>
</tr>
<tr>
<td class="sub1">3</td>
<td class="sub2">4</td>
<td class="sub3">0</td>
</tr>
<tr>
<td class="sub1">5</td>
<td class="sub2">6</td>
<td class="sub3">0</td>
</tr>
</tbody>
</table>
You haven't loaded the jQuery library in your fiddle. That's why your code doesn't work, otherwise your code does something. It gets the result of calculation and sets it to all .sub3 elements.
This is one way of getting the expected result.
$('.sub3').text(function() {
var $this = $(this);
var sub1 = +$this.siblings('.sub1').text();
var sub2 = +$this.siblings('.sub2').text();
return ((sub1 - sub2) / sub2).toFixed(2);
});
Here's a way to do it
var sub1 = [];
var sub2 = [];
var sub3 = [];
$(function subP() {
$('.sub1').each(function(i, e) {
sub1.push($(e).text());
});
$('.sub2').each(function(i, e) {
sub2.push($(e).text());
});
$('.sub3').each(function(i, e) {
var x = (sub1[i] - sub2[i]) / sub2[i];
$(this).html(x);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<th>test0</th>
<th>test1</th>
<th>test2</th>
<tr>
<td class="sub1">1</td>
<td class="sub2">2</td>
<td class="sub3">0</td>
</tr>
<tr>
<td class="sub1">3</td>
<td class="sub2">4</td>
<td class="sub3">0</td>
</tr>
<tr>
<td class="sub1">5</td>
<td class="sub2">6</td>
<td class="sub3">0</td>
</tr>
</tbody>
</table>

Looping through table cell ids in Javascript

I have created table cells in html that have ids that increment by 1 for example: cell1, cell2, cell3, ......, cell100.
What I would like to do is loop through and get reference to each of these cells using a for loop because referencing them one by one won't be good pratice and will require alot of codes of line, instead of this;
var cell1 = document.getElementById('cell1');
var cell2 = document.getElementById('cell2');
var cell3 = document.getElementById('cell3');
......
var cell100 = document.getElementById('cell100');
Is it possible to do something like this?
for (i = 0; i<=100; i++) {
var cell+i = document.getElementById("cell"+i);
// then I can call individual cells and assign tasks to them something along the lines of;
cell1.addEventListener('input',function(){}
cell5.background = '#f5f5f5'
cell55.innerHTML = 'I am cell 55'
etc..
}
EDITED:
Incase it might be useful, I have 1 table that contains many cells of which some have ids and some don't. I would only like to reference the ones that do have ids.
you can use document.querySelectorAll with a wildcard
var slice = Array.prorotype.slice;
var selection = document.querySelectorAll("[id^=cell]");
slice.call(selection).forEach(function(item, index){
// here item is the table row and index is the iteration number of forEach
// to get the id
var id = item.id;
//to get the numerical value in id
var number_in_id = item.id.match(/\d+/g)[0];
})
document.querySelectorAll("[id^=cell]") selectects all elements that their id starts with the string cell if you want to make it specific for table td's you add document.querySelectorAll("td[id^=cell]")
may be you are looking for this
var grid = document.getElementById("grid");//grid is the id of the table
for (var i = 1, row; row = grid.rows[i]; i++)
row.cells[0].textContent = "";//content of the starts with row 1..2..3 and so one than cell[0] or cell[1] and so on.
It'd be good pratice to use classes, though;
In base of your loop, you can do it so to get the current element, but if you have an loop more longer than the amount of the elements id numbers sequence, then it will be returning errors.
var Cell=document.getElementById("cell"+i)
//you've your DOM element in the variable called Cell now
//the one error you did is in the variable name
//you used the + operator in the variable name;
That's equivalent to element with id "cell0" when it's the first execution time of the loop. Not too elegant, you've many other ways to do the same.
Yes, it is quite easy, see below.
var cells = [];
for (var i = 0; i <= 100; i++) {
cells[i] = document.getElementById("cell"+i);
// do stuff....
if( cells[55] ) {
cells[55].innerHTML = 'I am cell 55';
}
}
Consider you have a table with an ID as myTable.
Get the table with,,
var theTable = document.getElementById('myTable');
To get all <td>s you could do,
var cells = theTable.querySelectorAll('td');
Then do the looping part,
for(var i = 0; i < cells.length; i++){
if(cells[i].id && cells[i].id.indexOf('cell') != -1){ //added to get only the significant cells
//do your stuff
cells[i].addEventListener(function(){});
cells[i].innerHTML = 'Something';
}
}
I'm lazy and didn't want to hand code any table, so I made Demo 2:
A form that'll accept a number of rows and columns
Can create <tr> and append to a table (0 to 100 rows)
Can create <td> and append to a <tr>(0 to 100 columns)
Assigns a unique id to every <tr> and <td>
The id pattern allows a human reader to locate <tr>s and <td>s
Each id for the <td> are displayed in each cell.
There's also two arrays, one for the <tr>(rowX) and one for the <td>(colY). There's many powerful methods for Array and having those 2 arrays you could even make a two-dimensional array.
Concerning the OP's request specifically about an id for cells on a table (complete or partial), I am aware that you have a pre-made table, so I'll take the key lines that make it possible in Demo 2 to assign ids:
row.setAttribute('id', 'r' + r);// Each row will have a numbered id (ex. r0 is row 1)
col.setAttribute('id', 'r' + r + 'c' + c);// Each cell will have a numbered id representing it's location (ex. r3c0 is located on row 4 column 1)
Demo 1
This snippet is an adaptation of the code previously mentioned:
function oddRows() {
var rows = document.querySelectorAll('tr');
// rows is a NodeList (an array-like object).
// We can covert this NodeList into an Array.
var rowArray = Array.prototype.slice.call(rows);
//Either way, NodeList or Array should be iterated through a for loop (most common way to reiterate)
for (var i = 0; i < rowArray.length; i++) {
if (i % 2 === 1) {
console.log(i);
var odd = rowArray[i];
odd.style.display = "none";
//This filters and removes all odd numbered rows
}
}
return false;
}
function evenCols() {
var cols = document.querySelectorAll('td');
var colArray = Array.prototype.slice.call(cols);
for (var j = 0; j < colArray.length; j++) {
if (j % 2 === 0) {
console.log(j);
var even = colArray[j];
even.style.backgroundColor = "red";
//This filters even numbered <td> and colors the background red.
}
}
return false;
}
td {
border: 2px inset #777;
}
button {
margin: 20px 5px 10px;
}
<button id="btn1" onclick="oddRows();">Remove Odd Rows</button>
<button id="btn2" onclick="evenCols();">Mark Even Cols</button>
<table id="t1">
<tr id="r0" class="row">
<td id="r0c0" class="col">r0c0</td>
<td id="r0c1" class="col">r0c1</td>
<td id="r0c2" class="col">r0c2</td>
<td id="r0c3" class="col">r0c3</td>
<td id="r0c4" class="col">r0c4</td>
<td id="r0c5" class="col">r0c5</td>
<td id="r0c6" class="col">r0c6</td>
<td id="r0c7" class="col">r0c7</td>
<td id="r0c8" class="col">r0c8</td>
<td id="r0c9" class="col">r0c9</td>
</tr>
<tr id="r1" class="row">
<td id="r1c0" class="col">r1c0</td>
<td id="r1c1" class="col">r1c1</td>
<td id="r1c2" class="col">r1c2</td>
<td id="r1c3" class="col">r1c3</td>
<td id="r1c4" class="col">r1c4</td>
<td id="r1c5" class="col">r1c5</td>
<td id="r1c6" class="col">r1c6</td>
<td id="r1c7" class="col">r1c7</td>
<td id="r1c8" class="col">r1c8</td>
<td id="r1c9" class="col">r1c9</td>
</tr>
<tr id="r2" class="row">
<td id="r2c0" class="col">r2c0</td>
<td id="r2c1" class="col">r2c1</td>
<td id="r2c2" class="col">r2c2</td>
<td id="r2c3" class="col">r2c3</td>
<td id="r2c4" class="col">r2c4</td>
<td id="r2c5" class="col">r2c5</td>
<td id="r2c6" class="col">r2c6</td>
<td id="r2c7" class="col">r2c7</td>
<td id="r2c8" class="col">r2c8</td>
<td id="r2c9" class="col">r2c9</td>
</tr>
<tr id="r3" class="row">
<td id="r3c0" class="col">r3c0</td>
<td id="r3c1" class="col">r3c1</td>
<td id="r3c2" class="col">r3c2</td>
<td id="r3c3" class="col">r3c3</td>
<td id="r3c4" class="col">r3c4</td>
<td id="r3c5" class="col">r3c5</td>
<td id="r3c6" class="col">r3c6</td>
<td id="r3c7" class="col">r3c7</td>
<td id="r3c8" class="col">r3c8</td>
<td id="r3c9" class="col">r3c9</td>
</tr>
<tr id="r4" class="row">
<td id="r4c0" class="col">r4c0</td>
<td id="r4c1" class="col">r4c1</td>
<td id="r4c2" class="col">r4c2</td>
<td id="r4c3" class="col">r4c3</td>
<td id="r4c4" class="col">r4c4</td>
<td id="r4c5" class="col">r4c5</td>
<td id="r4c6" class="col">r4c6</td>
<td id="r4c7" class="col">r4c7</td>
<td id="r4c8" class="col">r4c8</td>
<td id="r4c9" class="col">r4c9</td>
</tr>
<tr id="r5" class="row">
<td id="r5c0" class="col">r5c0</td>
<td id="r5c1" class="col">r5c1</td>
<td id="r5c2" class="col">r5c2</td>
<td id="r5c3" class="col">r5c3</td>
<td id="r5c4" class="col">r5c4</td>
<td id="r5c5" class="col">r5c5</td>
<td id="r5c6" class="col">r5c6</td>
<td id="r5c7" class="col">r5c7</td>
<td id="r5c8" class="col">r5c8</td>
<td id="r5c9" class="col">r5c9</td>
</tr>
<tr id="r6" class="row">
<td id="r6c0" class="col">r6c0</td>
<td id="r6c1" class="col">r6c1</td>
<td id="r6c2" class="col">r6c2</td>
<td id="r6c3" class="col">r6c3</td>
<td id="r6c4" class="col">r6c4</td>
<td id="r6c5" class="col">r6c5</td>
<td id="r6c6" class="col">r6c6</td>
<td id="r6c7" class="col">r6c7</td>
<td id="r6c8" class="col">r6c8</td>
<td id="r6c9" class="col">r6c9</td>
</tr>
<tr id="r7" class="row">
<td id="r7c0" class="col">r7c0</td>
<td id="r7c1" class="col">r7c1</td>
<td id="r7c2" class="col">r7c2</td>
<td id="r7c3" class="col">r7c3</td>
<td id="r7c4" class="col">r7c4</td>
<td id="r7c5" class="col">r7c5</td>
<td id="r7c6" class="col">r7c6</td>
<td id="r7c7" class="col">r7c7</td>
<td id="r7c8" class="col">r7c8</td>
<td id="r7c9" class="col">r7c9</td>
</tr>
<tr id="r8" class="row">
<td id="r8c0" class="col">r8c0</td>
<td id="r8c1" class="col">r8c1</td>
<td id="r8c2" class="col">r8c2</td>
<td id="r8c3" class="col">r8c3</td>
<td id="r8c4" class="col">r8c4</td>
<td id="r8c5" class="col">r8c5</td>
<td id="r8c6" class="col">r8c6</td>
<td id="r8c7" class="col">r8c7</td>
<td id="r8c8" class="col">r8c8</td>
<td id="r8c9" class="col">r8c9</td>
</tr>
<tr id="r9" class="row">
<td id="r9c0" class="col">r9c0</td>
<td id="r9c1" class="col">r9c1</td>
<td id="r9c2" class="col">r9c2</td>
<td id="r9c3" class="col">r9c3</td>
<td id="r9c4" class="col">r9c4</td>
<td id="r9c5" class="col">r9c5</td>
<td id="r9c6" class="col">r9c6</td>
<td id="r9c7" class="col">r9c7</td>
<td id="r9c8" class="col">r9c8</td>
<td id="r9c9" class="col">r9c9</td>
</tr>
</table>
If ids seem too heavy and cumbersome, you can select any cell on a table by using the pseudo-selectors nth-child and nth-of-type.
Example:
Target:* You want the 3rd <td> on the 5th row to have red text.
CSS:
table tbody tr:nth-of-type(5) td:nth-of-type(3) { color: red; }
jQuery:
$("table tbody tr:nth-of-type(5) td:nth-of-type(3)").css('color', 'red');
JavaScript:
var tgt = document.querySelector("table tbody tr:nth-of-type(5) td:nth-of-type(3)");
tgt.style.color = "red";
*Assuming that the target element has a table with a <tbody>
Demo 2
fieldset {
width: 50vw;
height: 55px;
margin: 10px auto;
padding: 3px;
}
input {
width: 40px;
height: 20px;
margin: 5px 10px;
}
table {
table-layout: fixed;
border-collapse: collapse;
border: 3px ridge #666;
width: 50vw;
height: 50vh;
margin: 20px auto;
}
td {
height: 20px;
width: 20px;
border: 1px inset grey;
font-size: 8px;
}
<fieldset>
<legend>Rows & Columns</legend>
<input id="rows" type="number" min="0" max="100" />
<input id="cols" type="number" min="0" max="100" />
<button id="btn1">Build</button>
</fieldset>
<table id="t1"></table>
<script>
var t1 = document.getElementById('t1');
var rows = document.getElementById('rows');
var cols = document.getElementById('cols');
var btn1 = document.getElementById('btn1');
btn1.addEventListener('click', function(e) {
var R = rows.value;
var C = cols.value;
var rowX = [];
var colY = [];
for (var r = 0; r < R; r++) {
var row = document.createElement('tr');
row.setAttribute('id', 'r' + r);// Each row will have a numbered id (ex. r0 is row 1)
row.classList.add('row');
rowX.push(row);
t1.appendChild(row)
for (var c = 0; c < C; c++) {
var col = document.createElement('td');
col.setAttribute('id', 'r' + r + 'c' + c);// Each cell will have a numbered id representing it's location (ex. r3c0 is located on row 4 column 1)
col.innerHTML = col.id;
col.classList.add('col');
colY.push(col);
row.appendChild(col);
}
}
}, false);
</script>

merging <td> rows in one column of html table

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>

Categories

Resources