I have create a table with pagination is every thing is fine and good but only one issue i have face and not finding any good solution can u please any body solve this and let us know where is the error int this code .
Issue is
if i click to s.no then shorting is not fine.
i used to this function for shorting _tableCustomFun.sortTable
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
my code is below .
myTableObjData = {
'head':['s.no', 'name', 'per%', 'price'],
'body': [
[1,'rohit', '9%', 23],
[10,'rohit azad', '19%', 230],
[8,'rohit', '39%', 111],
]
}
var _tableCustomFun = {
create_sample_table: function(parentNode, head, body, foot, data) {
if (typeof head == "undefined") {head = true;}
if (typeof body == "undefined") {body = true;}
if (typeof foot == "undefined") {foot = true;}
data = myTableObjData;
var table = document.createElement("table");
var tr, th, td;
// header
tr = document.createElement("tr");
var headers = data.head || [];
for (var i=0;i<headers.length;i++) {
th = document.createElement("th");
span = document.createElement("span");
span.innerHTML = headers[i];
th.appendChild(span);
tr.appendChild(th);
}
if (head) {
var thead = document.createElement("thead");
thead.appendChild(tr);
table.appendChild(thead);
} else {
table.appendChild(tr);
}
// end header
// body
var table_body = data.body || [];
if (body) {
var tbody = document.createElement("tbody");
}
for (var i=0;i<table_body.length;i++) {
tr = document.createElement("tr");
for (var j=0;j<table_body[i].length;j++) {
td = document.createElement("td");
td.innerHTML = table_body[i][j];
tr.appendChild(td);
}
if (body) {
tbody.appendChild(tr);
} else {
table.appendChild(tr);
}
}
if (body) {
table.appendChild(tbody);
}
// end body
if (parentNode) {
parentNode.innerHTML = "";
parentNode.appendChild(table);
}
//return table;
},
paginator: function(config) {
// throw errors if insufficient parameters were given
if (typeof config != "object")
throw "Paginator was expecting a config object!";
if (typeof config.get_rows != "function" && !(config.table instanceof Element))
throw "Paginator was expecting a table or get_row function!";
// get/set if things are disabled
if (typeof config.disable == "undefined") {
config.disable = false;
}
// get/make an element for storing the page numbers in
var box;
if (!(config.box instanceof Element)) {
config.box = document.createElement("div");
}
box = config.box;
// get/make function for getting table's rows
if (typeof config.get_rows != "function") {
config.get_rows = function () {
var table = config.table
var tbody = table.getElementsByTagName("tbody")[0]||table;
// get all the possible rows for paging
// exclude any rows that are just headers or empty
children = tbody.children;
var trs = [];
for (var i=0;i<children.length;i++) {
if (children[i].nodeType = "tr") {
if (children[i].getElementsByTagName("td").length > 0) {
trs.push(children[i]);
}
}
}
return trs;
}
}
var get_rows = config.get_rows;
var trs = get_rows();
// get/set rows per page
if (typeof config.rows_per_page == "undefined") {
var selects = box.getElementsByTagName("select");
if (typeof selects != "undefined" && (selects.length > 0 && typeof selects[0].selectedIndex != "undefined")) {
config.rows_per_page = selects[0].options[selects[0].selectedIndex].value;
} else {
config.rows_per_page = 150;
}
}
var rows_per_page = config.rows_per_page;
// get/set current page
if (typeof config.page == "undefined") {
config.page = 1;
}
var page = config.page;
// get page count
var pages = (rows_per_page > 0)? Math.ceil(trs.length / rows_per_page):1;
// check that page and page count are sensible values
if (pages < 1) {
pages = 1;
}
if (page > pages) {
page = pages;
}
if (page < 1) {
page = 1;
}
config.page = page;
// hide rows not on current page and show the rows that are
for (var i=0;i<trs.length;i++) {
if (typeof trs[i]["data-display"] == "undefined") {
trs[i]["data-display"] = trs[i].style.display||"";
}
if (rows_per_page > 0) {
if (i < page*rows_per_page && i >= (page-1)*rows_per_page) {
trs[i].style.display = trs[i]["data-display"];
} else {
// Only hide if pagination is not disabled
if (!config.disable) {
trs[i].style.display = "none";
} else {
trs[i].style.display = trs[i]["data-display"];
}
}
} else {
trs[i].style.display = trs[i]["data-display"];
}
}
// page button maker functions
config.active_class = config.active_class||"active";
if (typeof config.box_mode != "function" && config.box_mode != "list" && config.box_mode != "buttons") {
config.box_mode = "button";
}
if (typeof config.box_mode == "function") {
config.box_mode(config);
} else {
var make_button;
if (config.box_mode == "list") {
make_button = function (symbol, index, config, disabled, active) {
var li = document.createElement("li");
var a = document.createElement("a");
a.href = "#";
a.innerHTML = symbol;
a.addEventListener("click", function (event) {
event.preventDefault();
this.parentNode.click();
return false;
}, false);
li.appendChild(a);
var classes = [];
if (disabled) {
classes.push("disabled");
}
if (active) {
classes.push(config.active_class);
}
li.className = classes.join(" ");
li.addEventListener("click", function () {
if (this.className.split(" ").indexOf("disabled") == -1) {
config.page = index;
_tableCustomFun.paginator(config);
}
}, false);
return li;
}
} else {
make_button = function (symbol, index, config, disabled, active) {
var button = document.createElement("button");
button.innerHTML = symbol;
button.addEventListener("click", function (event) {
event.preventDefault();
if (this.disabled != true) {
config.page = index;
_tableCustomFun.paginator(config);
}
return false;
}, false);
if (disabled) {
button.disabled = true;
}
if (active) {
button.className = config.active_class;
}
return button;
}
}
// make page button collection
var page_box = document.createElement(config.box_mode == "list"?"ul":"div");
if (config.box_mode == "list") {
page_box.className = "pagination";
}
var left = make_button("«", (page>1?page-1:1), config, (page == 1), false);
page_box.appendChild(left);
for (var i=1;i<=pages;i++) {
var li = make_button(i, i, config, false, (page == i));
page_box.appendChild(li);
}
var right = make_button("»", (pages>page?page+1:page), config, (page == pages), false);
page_box.appendChild(right);
if (box.childNodes.length) {
while (box.childNodes.length > 1) {
box.removeChild(box.childNodes[0]);
}
box.replaceChild(page_box, box.childNodes[0]);
} else {
box.appendChild(page_box);
}
}
// make rows per page selector
if (!(typeof config.page_options == "boolean" && !config.page_options)) {
if (typeof config.page_options == "undefined") {
config.page_options = [
{ value: 10, text: '10' },
{ value: 20, text: '20' },
{ value: 50, text: '50' },
{ value: 100,text: '100' },
{ value: 0, text: 'All' }
];
}
var options = config.page_options;
var select = document.createElement("select");
for (var i=0;i<options.length;i++) {
var o = document.createElement("option");
o.value = options[i].value;
o.text = options[i].text;
select.appendChild(o);
}
select.value = rows_per_page;
select.addEventListener("change", function () {
config.rows_per_page = this.value;
_tableCustomFun.paginator(config);
}, false);
box.appendChild(select);
}
// status message
var stat = document.createElement("span");
stat.innerHTML = "On page " + page + " of " + pages
+ ", showing rows " + (((page-1)*rows_per_page)+1)
+ " to " + (trs.length<page*rows_per_page||rows_per_page==0?trs.length:page*rows_per_page)
+ " of " + trs.length;
box.appendChild(stat);
// hide pagination if disabled
if (config.disable) {
if (typeof box["data-display"] == "undefined") {
box["data-display"] = box.style.display||"";
}
box.style.display = "none";
} else {
if (box.style.display == "none") {
box.style.display = box["data-display"]||"";
}
}
// run tail function
if (typeof config.tail_call == "function") {
config.tail_call(config);
}
return box;
},
sortTable: function(table, col, reverse) {
_tableCustomFun.addShortingClass(table, col, reverse);
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
},
makeSortable: function(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {_tableCustomFun.sortTable(table, i, (dir = 1 - dir))});
}(i));
},
makeAllSortable: function(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) _tableCustomFun.makeSortable(t[i]);
},
addShortingClass: function(table, col, reverse){
var thPosition = table.tHead.rows[0].cells[col];
console.log(reverse);
console.log(thPosition);
var _thead = table.tHead.rows[0]
for (var i = 0; i < _thead.cells.length; i++) {
_thead.cells[i].removeAttribute("class");
}
thPosition.classList.add("shorting");
if(reverse == 1){
thPosition.classList.add("up");
}else{
thPosition.classList.add("down");
}
},
init: function(){
var tableNode = document.getElementById("table_box_native");
if(tableNode){
_tableCustomFun.addCssFile();
_tableCustomFun.create_sample_table(document.getElementById("table_box_native"));
_tableCustomFun.paginator({
table: document.getElementById("table_box_native").getElementsByTagName("table")[0],
box: document.getElementById("index_native"),
active_class: "color_page"
});
_tableCustomFun.makeAllSortable();
}
},
addCssFile: function(){
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'css_tablecustom.cms?v=7&minify=1';
link.media = 'all';
head.appendChild(link);
}
}
}
// window.onload = function () {
// _tableCustomFun.init();
// };
document.addEventListener('DOMContentLoaded', function(){_tableCustomFun.init()})
<div id="table_box_native" class="tableBox">
</div>
<div id="index_native" class="box tableDataBox"></div>
The issue is with .localCompare.
Following is the sample:
function test(v1, v2) {
console.log(v1.toString().localeCompare(v2.toString()))
}
test(1, 8)
test(1, 10)
test(8, 1)
test(8, 10) // This returns 1 instead of -1
test(10, 1)
test(10, 8)
Since you have numeric values,its always better to convert values to number and process it.
tr = tr.sort(function(a, b) { // sort rows
var v1 = a.cells[col].textContent.trim();
var v2 = b.cells[col].textContent.trim()
return reverse * (v1 - v2);
});
Sample:
myTableObjData = {
'head': ['s.no', 'name', 'per%', 'price'],
'body': [
[1, 'rohit', '9%', 23],
[10, 'rohit azad', '19%', 230],
[8, 'rohit', '39%', 111],
]
}
var _tableCustomFun = {
create_sample_table: function(parentNode, head, body, foot, data) {
if (typeof head == "undefined") {
head = true;
}
if (typeof body == "undefined") {
body = true;
}
if (typeof foot == "undefined") {
foot = true;
}
data = myTableObjData;
var table = document.createElement("table");
var tr, th, td;
// header
tr = document.createElement("tr");
var headers = data.head || [];
for (var i = 0; i < headers.length; i++) {
th = document.createElement("th");
span = document.createElement("span");
span.innerHTML = headers[i];
th.appendChild(span);
tr.appendChild(th);
}
if (head) {
var thead = document.createElement("thead");
thead.appendChild(tr);
table.appendChild(thead);
} else {
table.appendChild(tr);
}
// end header
// body
var table_body = data.body || [];
if (body) {
var tbody = document.createElement("tbody");
}
for (var i = 0; i < table_body.length; i++) {
tr = document.createElement("tr");
for (var j = 0; j < table_body[i].length; j++) {
td = document.createElement("td");
td.innerHTML = table_body[i][j];
tr.appendChild(td);
}
if (body) {
tbody.appendChild(tr);
} else {
table.appendChild(tr);
}
}
if (body) {
table.appendChild(tbody);
}
// end body
if (parentNode) {
parentNode.innerHTML = "";
parentNode.appendChild(table);
}
//return table;
},
paginator: function(config) {
// throw errors if insufficient parameters were given
if (typeof config != "object")
throw "Paginator was expecting a config object!";
if (typeof config.get_rows != "function" && !(config.table instanceof Element))
throw "Paginator was expecting a table or get_row function!";
// get/set if things are disabled
if (typeof config.disable == "undefined") {
config.disable = false;
}
// get/make an element for storing the page numbers in
var box;
if (!(config.box instanceof Element)) {
config.box = document.createElement("div");
}
box = config.box;
// get/make function for getting table's rows
if (typeof config.get_rows != "function") {
config.get_rows = function() {
var table = config.table
var tbody = table.getElementsByTagName("tbody")[0] || table;
// get all the possible rows for paging
// exclude any rows that are just headers or empty
children = tbody.children;
var trs = [];
for (var i = 0; i < children.length; i++) {
if (children[i].nodeType = "tr") {
if (children[i].getElementsByTagName("td").length > 0) {
trs.push(children[i]);
}
}
}
return trs;
}
}
var get_rows = config.get_rows;
var trs = get_rows();
// get/set rows per page
if (typeof config.rows_per_page == "undefined") {
var selects = box.getElementsByTagName("select");
if (typeof selects != "undefined" && (selects.length > 0 && typeof selects[0].selectedIndex != "undefined")) {
config.rows_per_page = selects[0].options[selects[0].selectedIndex].value;
} else {
config.rows_per_page = 150;
}
}
var rows_per_page = config.rows_per_page;
// get/set current page
if (typeof config.page == "undefined") {
config.page = 1;
}
var page = config.page;
// get page count
var pages = (rows_per_page > 0) ? Math.ceil(trs.length / rows_per_page) : 1;
// check that page and page count are sensible values
if (pages < 1) {
pages = 1;
}
if (page > pages) {
page = pages;
}
if (page < 1) {
page = 1;
}
config.page = page;
// hide rows not on current page and show the rows that are
for (var i = 0; i < trs.length; i++) {
if (typeof trs[i]["data-display"] == "undefined") {
trs[i]["data-display"] = trs[i].style.display || "";
}
if (rows_per_page > 0) {
if (i < page * rows_per_page && i >= (page - 1) * rows_per_page) {
trs[i].style.display = trs[i]["data-display"];
} else {
// Only hide if pagination is not disabled
if (!config.disable) {
trs[i].style.display = "none";
} else {
trs[i].style.display = trs[i]["data-display"];
}
}
} else {
trs[i].style.display = trs[i]["data-display"];
}
}
// page button maker functions
config.active_class = config.active_class || "active";
if (typeof config.box_mode != "function" && config.box_mode != "list" && config.box_mode != "buttons") {
config.box_mode = "button";
}
if (typeof config.box_mode == "function") {
config.box_mode(config);
} else {
var make_button;
if (config.box_mode == "list") {
make_button = function(symbol, index, config, disabled, active) {
var li = document.createElement("li");
var a = document.createElement("a");
a.href = "#";
a.innerHTML = symbol;
a.addEventListener("click", function(event) {
event.preventDefault();
this.parentNode.click();
return false;
}, false);
li.appendChild(a);
var classes = [];
if (disabled) {
classes.push("disabled");
}
if (active) {
classes.push(config.active_class);
}
li.className = classes.join(" ");
li.addEventListener("click", function() {
if (this.className.split(" ").indexOf("disabled") == -1) {
config.page = index;
_tableCustomFun.paginator(config);
}
}, false);
return li;
}
} else {
make_button = function(symbol, index, config, disabled, active) {
var button = document.createElement("button");
button.innerHTML = symbol;
button.addEventListener("click", function(event) {
event.preventDefault();
if (this.disabled != true) {
config.page = index;
_tableCustomFun.paginator(config);
}
return false;
}, false);
if (disabled) {
button.disabled = true;
}
if (active) {
button.className = config.active_class;
}
return button;
}
}
// make page button collection
var page_box = document.createElement(config.box_mode == "list" ? "ul" : "div");
if (config.box_mode == "list") {
page_box.className = "pagination";
}
var left = make_button("«", (page > 1 ? page - 1 : 1), config, (page == 1), false);
page_box.appendChild(left);
for (var i = 1; i <= pages; i++) {
var li = make_button(i, i, config, false, (page == i));
page_box.appendChild(li);
}
var right = make_button("»", (pages > page ? page + 1 : page), config, (page == pages), false);
page_box.appendChild(right);
if (box.childNodes.length) {
while (box.childNodes.length > 1) {
box.removeChild(box.childNodes[0]);
}
box.replaceChild(page_box, box.childNodes[0]);
} else {
box.appendChild(page_box);
}
}
// make rows per page selector
if (!(typeof config.page_options == "boolean" && !config.page_options)) {
if (typeof config.page_options == "undefined") {
config.page_options = [{
value: 10,
text: '10'
},
{
value: 20,
text: '20'
},
{
value: 50,
text: '50'
},
{
value: 100,
text: '100'
},
{
value: 0,
text: 'All'
}
];
}
var options = config.page_options;
var select = document.createElement("select");
for (var i = 0; i < options.length; i++) {
var o = document.createElement("option");
o.value = options[i].value;
o.text = options[i].text;
select.appendChild(o);
}
select.value = rows_per_page;
select.addEventListener("change", function() {
config.rows_per_page = this.value;
_tableCustomFun.paginator(config);
}, false);
box.appendChild(select);
}
// status message
var stat = document.createElement("span");
stat.innerHTML = "On page " + page + " of " + pages +
", showing rows " + (((page - 1) * rows_per_page) + 1) +
" to " + (trs.length < page * rows_per_page || rows_per_page == 0 ? trs.length : page * rows_per_page) +
" of " + trs.length;
box.appendChild(stat);
// hide pagination if disabled
if (config.disable) {
if (typeof box["data-display"] == "undefined") {
box["data-display"] = box.style.display || "";
}
box.style.display = "none";
} else {
if (box.style.display == "none") {
box.style.display = box["data-display"] || "";
}
}
// run tail function
if (typeof config.tail_call == "function") {
config.tail_call(config);
}
return box;
},
sortTable: function(table, col, reverse) {
_tableCustomFun.addShortingClass(table, col, reverse);
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function(a, b) { // sort rows
var v1 = a.cells[col].textContent.trim();
var v2 = b.cells[col].textContent.trim()
return reverse * (v1 - v2 );
});
for (i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
},
makeSortable: function(table) {
var th = table.tHead,
i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0)(function(i) {
var dir = 1;
th[i].addEventListener('click', function() {
_tableCustomFun.sortTable(table, i, (dir = 1 - dir))
});
}(i));
},
makeAllSortable: function(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'),
i = t.length;
while (--i >= 0) _tableCustomFun.makeSortable(t[i]);
},
addShortingClass: function(table, col, reverse) {
var thPosition = table.tHead.rows[0].cells[col];
console.log(reverse);
console.log(thPosition);
var _thead = table.tHead.rows[0]
for (var i = 0; i < _thead.cells.length; i++) {
_thead.cells[i].removeAttribute("class");
}
thPosition.classList.add("shorting");
if (reverse == 1) {
thPosition.classList.add("up");
} else {
thPosition.classList.add("down");
}
},
init: function() {
var tableNode = document.getElementById("table_box_native");
if (tableNode) {
_tableCustomFun.addCssFile();
_tableCustomFun.create_sample_table(document.getElementById("table_box_native"));
_tableCustomFun.paginator({
table: document.getElementById("table_box_native").getElementsByTagName("table")[0],
box: document.getElementById("index_native"),
active_class: "color_page"
});
_tableCustomFun.makeAllSortable();
}
},
addCssFile: function() {
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId)) {
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'css_tablecustom.cms?v=7&minify=1';
link.media = 'all';
head.appendChild(link);
}
}
}
// window.onload = function () {
// _tableCustomFun.init();
// };
document.addEventListener('DOMContentLoaded', function() {
_tableCustomFun.init()
})
<div id="table_box_native" class="tableBox">
</div>
<div id="index_native" class="box tableDataBox"></div>
You have to sort the table based on columns data type (number and string). You can do so by checking the column index:
.......
tr = tr.sort(function (a, b) { // sort rows
if(col == 0 || col == 3){
return reverse * (+a.cells[col].textContent.trim() - +b.cells[col].textContent.trim());
}
else{
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
}
});
........
myTableObjData = {
'head':['s.no', 'name', 'per%', 'price'],
'body': [
[1,'rohit', '9%', 23],
[10,'rohit azad', '19%', 230],
[8,'rohit', '39%', 111],
]
}
var _tableCustomFun = {
create_sample_table: function(parentNode, head, body, foot, data) {
if (typeof head == "undefined") {head = true;}
if (typeof body == "undefined") {body = true;}
if (typeof foot == "undefined") {foot = true;}
data = myTableObjData;
var table = document.createElement("table");
var tr, th, td;
// header
tr = document.createElement("tr");
var headers = data.head || [];
for (var i=0;i<headers.length;i++) {
th = document.createElement("th");
span = document.createElement("span");
span.innerHTML = headers[i];
th.appendChild(span);
tr.appendChild(th);
}
if (head) {
var thead = document.createElement("thead");
thead.appendChild(tr);
table.appendChild(thead);
} else {
table.appendChild(tr);
}
// end header
// body
var table_body = data.body || [];
if (body) {
var tbody = document.createElement("tbody");
}
for (var i=0;i<table_body.length;i++) {
tr = document.createElement("tr");
for (var j=0;j<table_body[i].length;j++) {
td = document.createElement("td");
td.innerHTML = table_body[i][j];
tr.appendChild(td);
}
if (body) {
tbody.appendChild(tr);
} else {
table.appendChild(tr);
}
}
if (body) {
table.appendChild(tbody);
}
// end body
if (parentNode) {
parentNode.innerHTML = "";
parentNode.appendChild(table);
}
//return table;
},
paginator: function(config) {
// throw errors if insufficient parameters were given
if (typeof config != "object")
throw "Paginator was expecting a config object!";
if (typeof config.get_rows != "function" && !(config.table instanceof Element))
throw "Paginator was expecting a table or get_row function!";
// get/set if things are disabled
if (typeof config.disable == "undefined") {
config.disable = false;
}
// get/make an element for storing the page numbers in
var box;
if (!(config.box instanceof Element)) {
config.box = document.createElement("div");
}
box = config.box;
// get/make function for getting table's rows
if (typeof config.get_rows != "function") {
config.get_rows = function () {
var table = config.table
var tbody = table.getElementsByTagName("tbody")[0]||table;
// get all the possible rows for paging
// exclude any rows that are just headers or empty
children = tbody.children;
var trs = [];
for (var i=0;i<children.length;i++) {
if (children[i].nodeType = "tr") {
if (children[i].getElementsByTagName("td").length > 0) {
trs.push(children[i]);
}
}
}
return trs;
}
}
var get_rows = config.get_rows;
var trs = get_rows();
// get/set rows per page
if (typeof config.rows_per_page == "undefined") {
var selects = box.getElementsByTagName("select");
if (typeof selects != "undefined" && (selects.length > 0 && typeof selects[0].selectedIndex != "undefined")) {
config.rows_per_page = selects[0].options[selects[0].selectedIndex].value;
} else {
config.rows_per_page = 150;
}
}
var rows_per_page = config.rows_per_page;
// get/set current page
if (typeof config.page == "undefined") {
config.page = 1;
}
var page = config.page;
// get page count
var pages = (rows_per_page > 0)? Math.ceil(trs.length / rows_per_page):1;
// check that page and page count are sensible values
if (pages < 1) {
pages = 1;
}
if (page > pages) {
page = pages;
}
if (page < 1) {
page = 1;
}
config.page = page;
// hide rows not on current page and show the rows that are
for (var i=0;i<trs.length;i++) {
if (typeof trs[i]["data-display"] == "undefined") {
trs[i]["data-display"] = trs[i].style.display||"";
}
if (rows_per_page > 0) {
if (i < page*rows_per_page && i >= (page-1)*rows_per_page) {
trs[i].style.display = trs[i]["data-display"];
} else {
// Only hide if pagination is not disabled
if (!config.disable) {
trs[i].style.display = "none";
} else {
trs[i].style.display = trs[i]["data-display"];
}
}
} else {
trs[i].style.display = trs[i]["data-display"];
}
}
// page button maker functions
config.active_class = config.active_class||"active";
if (typeof config.box_mode != "function" && config.box_mode != "list" && config.box_mode != "buttons") {
config.box_mode = "button";
}
if (typeof config.box_mode == "function") {
config.box_mode(config);
} else {
var make_button;
if (config.box_mode == "list") {
make_button = function (symbol, index, config, disabled, active) {
var li = document.createElement("li");
var a = document.createElement("a");
a.href = "#";
a.innerHTML = symbol;
a.addEventListener("click", function (event) {
event.preventDefault();
this.parentNode.click();
return false;
}, false);
li.appendChild(a);
var classes = [];
if (disabled) {
classes.push("disabled");
}
if (active) {
classes.push(config.active_class);
}
li.className = classes.join(" ");
li.addEventListener("click", function () {
if (this.className.split(" ").indexOf("disabled") == -1) {
config.page = index;
_tableCustomFun.paginator(config);
}
}, false);
return li;
}
} else {
make_button = function (symbol, index, config, disabled, active) {
var button = document.createElement("button");
button.innerHTML = symbol;
button.addEventListener("click", function (event) {
event.preventDefault();
if (this.disabled != true) {
config.page = index;
_tableCustomFun.paginator(config);
}
return false;
}, false);
if (disabled) {
button.disabled = true;
}
if (active) {
button.className = config.active_class;
}
return button;
}
}
// make page button collection
var page_box = document.createElement(config.box_mode == "list"?"ul":"div");
if (config.box_mode == "list") {
page_box.className = "pagination";
}
var left = make_button("«", (page>1?page-1:1), config, (page == 1), false);
page_box.appendChild(left);
for (var i=1;i<=pages;i++) {
var li = make_button(i, i, config, false, (page == i));
page_box.appendChild(li);
}
var right = make_button("»", (pages>page?page+1:page), config, (page == pages), false);
page_box.appendChild(right);
if (box.childNodes.length) {
while (box.childNodes.length > 1) {
box.removeChild(box.childNodes[0]);
}
box.replaceChild(page_box, box.childNodes[0]);
} else {
box.appendChild(page_box);
}
}
// make rows per page selector
if (!(typeof config.page_options == "boolean" && !config.page_options)) {
if (typeof config.page_options == "undefined") {
config.page_options = [
{ value: 10, text: '10' },
{ value: 20, text: '20' },
{ value: 50, text: '50' },
{ value: 100,text: '100' },
{ value: 0, text: 'All' }
];
}
var options = config.page_options;
var select = document.createElement("select");
for (var i=0;i<options.length;i++) {
var o = document.createElement("option");
o.value = options[i].value;
o.text = options[i].text;
select.appendChild(o);
}
select.value = rows_per_page;
select.addEventListener("change", function () {
config.rows_per_page = this.value;
_tableCustomFun.paginator(config);
}, false);
box.appendChild(select);
}
// status message
var stat = document.createElement("span");
stat.innerHTML = "On page " + page + " of " + pages
+ ", showing rows " + (((page-1)*rows_per_page)+1)
+ " to " + (trs.length<page*rows_per_page||rows_per_page==0?trs.length:page*rows_per_page)
+ " of " + trs.length;
box.appendChild(stat);
// hide pagination if disabled
if (config.disable) {
if (typeof box["data-display"] == "undefined") {
box["data-display"] = box.style.display||"";
}
box.style.display = "none";
} else {
if (box.style.display == "none") {
box.style.display = box["data-display"]||"";
}
}
// run tail function
if (typeof config.tail_call == "function") {
config.tail_call(config);
}
return box;
},
sortTable: function(table, col, reverse) {
_tableCustomFun.addShortingClass(table, col, reverse);
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
if(col == 0 || col == 3){
return reverse * (+a.cells[col].textContent.trim() - +b.cells[col].textContent.trim());
}
else{
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
}
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
},
makeSortable: function(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {_tableCustomFun.sortTable(table, i, (dir = 1 - dir))});
}(i));
},
makeAllSortable: function(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) _tableCustomFun.makeSortable(t[i]);
},
addShortingClass: function(table, col, reverse){
var thPosition = table.tHead.rows[0].cells[col];
//console.log(reverse);
//console.log(thPosition);
var _thead = table.tHead.rows[0]
for (var i = 0; i < _thead.cells.length; i++) {
_thead.cells[i].removeAttribute("class");
}
thPosition.classList.add("shorting");
if(reverse == 1){
thPosition.classList.add("up");
}else{
thPosition.classList.add("down");
}
},
init: function(){
var tableNode = document.getElementById("table_box_native");
if(tableNode){
_tableCustomFun.addCssFile();
_tableCustomFun.create_sample_table(document.getElementById("table_box_native"));
_tableCustomFun.paginator({
table: document.getElementById("table_box_native").getElementsByTagName("table")[0],
box: document.getElementById("index_native"),
active_class: "color_page"
});
_tableCustomFun.makeAllSortable();
}
},
addCssFile: function(){
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'css_tablecustom.cms?v=7&minify=1';
link.media = 'all';
head.appendChild(link);
}
}
}
// window.onload = function () {
// _tableCustomFun.init();
// };
document.addEventListener('DOMContentLoaded', function(){_tableCustomFun.init()})
<div id="table_box_native" class="tableBox">
</div>
<div id="index_native" class="box tableDataBox"></div>
There is a strange behavior with DOMParser. When I use "text/xml" as the parameter I get my object and each time I use a child (like parentNodes), the child is itself a DOM object. However, when I use "text/html" as the parameter, the children are not DOM objects. Why is that and how can I have DOM objects for all the children?
Here is what I do:
parser = new DOMParser();
doc = parser.parseFromString(stringContainingHTMLSource, "text/html").getElementsByTagName('p');
console.log(doc[0].childNodes[0]);
My childNode returns the element but not as a DOM object...
Edit:
Here are my recursive functions:
var getParents = function(node, parentNodes){
if(node.nodeName == 'span'){
parentNodes.push(node.attributes[0].nodeValue);
} else if(node.nodeName == 'p' && node.attributes.length > 0) {
parentNodes.push(node.nodeName);
parentNodes.push(node.attributes[0].nodeValue);
} else {
parentNodes.push(node.nodeName);
}
if(node.parentNode.nodeName != '#document'){
getParents(node.parentNode, parentNodes);
}
return parentNodes;
};
var parse = function(node, vertical, horizontal, paragraph){
if(node.childNodes.length > 0){
for(var int = 0; int < node.childNodes.length; int++){
parse(node.childNodes[int], vertical, horizontal, paragraph);
}
} else{
var object = {};
var attributes = getParents(node, []);
for(var int = 0; int < attributes.length; int++) {
// right alignment
if(/text-align/i.test(attributes[int])){
object.alignment = attributes[int].split(": ")[1].replace(';','');
} else if (/color/i.test(attributes[int])) {
// color
object.color = attributes[int].split(":")[1];
} else if (attributes[int] == 'em') {
// italic
if (object.italics) {
delete object.bold;
object.bolditalics = true;
} else {
object.italics = true;
}
} else if (attributes[int] == 'strong') {
// bold
if (object.italics) {
delete object.italics;
object.bolditalics = true;
} else {
object.bold = true;
}
} else if (attributes[int] == 'u') {
// underline
object.decoration = 'underline';
} else if (attributes[int] == 's') {
// strike
object.decoration = 'lineThrough';
}
}
object.text = node.textContent;
pdfContent[vertical][horizontal].push(object);
}
};
for(var vertical = 0; vertical < payment.htmlContent.length; vertical++) {
for(var horizontal = 0; horizontal < payment.htmlContent[vertical].length; horizontal++) {
var parser = new DOMParser();
var paragraphs = parser.parseFromString(payment.htmlContent[vertical][horizontal], "text/xml").getElementsByTagName('p');
for (var paragraph = 0; paragraph < paragraphs.length; paragraph++) {
for (var num = 0; num < paragraphs[paragraph].childNodes.length; num++) {
parse(paragraphs[paragraph].childNodes[num], vertical, horizontal, paragraph);
}
}
}
}
I made a few assumptions on what the values are and after I Added a few verifications like if(node.attributes.length>0)into your code, it seems to work.
var payment={htmlContent:[['<p>some<em>text</em></p>', '<p>some<span>text<strong>here</strong></span></p>'],['<p>some<s>text</s></p>', '<p>some<span style="color:#FF00FF">text</span></p>']]};
var getParents = function(node, parentNodes){
if(node.nodeName == 'span'){
if(node.attributes.length>0)
parentNodes.push(node.attributes[0].nodeValue);
} else if(node.nodeName == 'p' && node.attributes.length > 0) {
parentNodes.push(node.nodeName);
if(node.attributes.length>0)
parentNodes.push(node.attributes[0].nodeValue);
} else {
parentNodes.push(node.nodeName);
}
if(node.parentNode.nodeName != '#document'){
getParents(node.parentNode, parentNodes);
}
return parentNodes;
};
var parse = function(node, vertical, horizontal, paragraph){
if(node.childNodes.length > 0){
for(var int = 0; int < node.childNodes.length; int++){
parse(node.childNodes[int], vertical, horizontal, paragraph);
}
} else{
var object = {};
var attributes = getParents(node, []);
console.log(attributes);
for(var int = 0; int < attributes.length; int++) {
// right alignment
if(/text-align/i.test(attributes[int])){
object.alignment = attributes[int].split(": ")[1].replace(';','');
} else if (/color/i.test(attributes[int])) {
// color
object.color = attributes[int].split(":")[1];
} else if (attributes[int] == 'em') {
// italic
if (object.italics) {
delete object.bold;
object.bolditalics = true;
} else {
object.italics = true;
}
} else if (attributes[int] == 'strong') {
// bold
if (object.italics) {
delete object.italics;
object.bolditalics = true;
} else {
object.bold = true;
}
} else if (attributes[int] == 'u') {
// underline
object.decoration = 'underline';
} else if (attributes[int] == 's') {
// strike
object.decoration = 'lineThrough';
}
}
object.text = node.textContent;
if(!pdfContent[vertical])pdfContent[vertical]=[];
if(!pdfContent[vertical][horizontal])
pdfContent[vertical][horizontal]=[];
pdfContent[vertical][horizontal].push(object);
}
};
var pdfContent = [];
for(var vertical = 0; vertical < payment.htmlContent.length; vertical++) {
for(var horizontal = 0; horizontal < payment.htmlContent[vertical].length; horizontal++) {
var parser = new DOMParser();
var paragraphs = parser.parseFromString(payment.htmlContent[vertical][horizontal], "text/xml").getElementsByTagName('p');
for (var paragraph = 0; paragraph < paragraphs.length; paragraph++) {
for (var num = 0; num < paragraphs[paragraph].childNodes.length; num++) {
parse(paragraphs[paragraph].childNodes[num], vertical, horizontal, paragraph);
}
}
}
}
for(var i=0; i<pdfContent.length; i++){
for(var j=0; j<pdfContent[i].length; j++){
document.querySelector('#log').textContent+=pdfContent[i][j].toSource();
}
}
<p id="log"></p>