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>
While we adding HTML into the HTML output render has in the DIV. If we added something like following
<div class="test" w3-include-html="template_build/header/header-classic.html"></div>
But the output render has incldued that
<div class="test">MY INCLUDED CONTENT</div>
I want to remove that div class="test" on rendering process on w3data.js.
Can someone help me?
Snippet 1 features a simple function that removes any given attribute from any given element. Snippet 2 is the w3data.js with an extra line at 126:
elmnt.removeAttribute("class");
You may use either one to get the same result
SNIPPET 1
removeAttr(".test", "class");
function removeAttr(target, attribute) {
var target = document.querySelector(target);
target.removeAttribute(attribute);
}
.test { color:red }
<div class="test">THIS CONTENT SHOULD BE BLACK TEXT, NOT RED</div>
SNIPPET 2
/* W3Data ver 1.31 by W3Schools.com */
var w3DataObject = {};
function w3DisplayData(id, data) {
var htmlObj, htmlTemplate, html, arr = [],
a, l, rowClone, x, j, i, ii, cc, repeat, repeatObj, repeatX = "";
htmlObj = document.getElementById(id);
htmlTemplate = w3InitTemplate(id, htmlObj);
html = htmlTemplate.cloneNode(true);
arr = w3GetElementsByAttribute(html, "w3-repeat");
l = arr.length;
for (j = (l - 1); j >= 0; j -= 1) {
cc = arr[j].getAttribute("w3-repeat").split(" ");
if (cc.length == 1) {
repeat = cc[0];
} else {
repeatX = cc[0];
repeat = cc[2];
}
arr[j].removeAttribute("w3-repeat");
repeatObj = data[repeat];
if (repeatObj && typeof repeatObj == "object" && repeatObj.length != "undefined") {
i = 0;
for (x in repeatObj) {
i += 1;
rowClone = arr[j];
rowClone = w3NeedleInHaystack(rowClone, "element", repeatX, repeatObj[x]);
a = rowClone.attributes;
for (ii = 0; ii < a.length; ii += 1) {
a[ii].value = w3NeedleInHaystack(a[ii], "attribute", repeatX, repeatObj[x]).value;
}
(i === repeatObj.length) ? arr[j].parentNode.replaceChild(rowClone, arr[j]): arr[j].parentNode.insertBefore(rowClone, arr[j]);
}
} else {
console.log("w3-repeat must be an array. " + repeat + " is not an array.");
continue;
}
}
html = w3NeedleInHaystack(html, "element");
htmlObj.parentNode.replaceChild(html, htmlObj);
function w3InitTemplate(id, obj) {
var template;
template = obj.cloneNode(true);
if (w3DataObject.hasOwnProperty(id)) {
return w3DataObject[id];
}
w3DataObject[id] = template;
return template;
}
function w3GetElementsByAttribute(x, att) {
var arr = [],
arrCount = -1,
i, l, y = x.getElementsByTagName("*"),
z = att.toUpperCase();
l = y.length;
for (i = -1; i < l; i += 1) {
if (i == -1) {
y[i] = x;
}
if (y[i].getAttribute(z) !== null) {
arrCount += 1;
arr[arrCount] = y[i];
}
}
return arr;
}
function w3NeedleInHaystack(elmnt, typ, repeatX, x) {
var value, rowClone, pos1, haystack, pos2, needle = [],
needleToReplace, i, cc, r;
rowClone = elmnt.cloneNode(true);
pos1 = 0;
while (pos1 > -1) {
haystack = (typ == "attribute") ? rowClone.value : rowClone.innerHTML;
pos1 = haystack.indexOf("{{", pos1);
if (pos1 === -1) {
break;
}
pos2 = haystack.indexOf("}}", pos1 + 1);
needleToReplace = haystack.substring(pos1 + 2, pos2);
needle = needleToReplace.split("||");
value = undefined;
for (i = 0; i < needle.length; i += 1) {
needle[i] = needle[i].replace(/^\s+|\s+$/gm, ''); //trim
//value = ((x && x[needle[i]]) || (data && data[needle[i]]));
if (x) {
value = x[needle[i]];
}
if (value == undefined && data) {
value = data[needle[i]];
}
if (value == undefined) {
cc = needle[i].split(".");
if (cc[0] == repeatX) {
value = x[cc[1]];
}
}
if (value == undefined) {
if (needle[i] == repeatX) {
value = x;
}
}
if (value == undefined) {
if (needle[i].substr(0, 1) == '"') {
value = needle[i].replace(/"/g, "");
} else if (needle[i].substr(0, 1) == "'") {
value = needle[i].replace(/'/g, "");
}
}
if (value != undefined) {
break;
}
}
if (value != undefined) {
r = "{{" + needleToReplace + "}}";
if (typ == "attribute") {
rowClone.value = rowClone.value.replace(r, value);
} else {
w3ReplaceHTML(rowClone, r, value);
}
}
pos1 = pos1 + 1;
}
return rowClone;
}
function w3ReplaceHTML(a, r, result) {
var b, l, i, a, x, j;
if (a.hasAttributes()) {
b = a.attributes;
l = b.length;
for (i = 0; i < l; i += 1) {
if (b[i].value.indexOf(r) > -1) {
b[i].value = b[i].value.replace(r, result);
}
}
}
x = a.getElementsByTagName("*");
l = x.length;
a.innerHTML = a.innerHTML.replace(r, result);
}
}
function w3IncludeHTML() {
var z, i, elmnt, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
file = elmnt.getAttribute("w3-include-html");
if (file) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
elmnt.innerHTML = this.responseText;
elmnt.removeAttribute("w3-include-html");
elmnt.removeAttribute("class"); // Add this expression
w3IncludeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
function w3Http(target, readyfunc, xml, method) {
var httpObj;
if (!method) {
method = "GET";
}
if (window.XMLHttpRequest) {
httpObj = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
if (httpObj) {
if (readyfunc) {
httpObj.onreadystatechange = readyfunc;
}
httpObj.open(method, target, true);
httpObj.send(xml);
}
}
I would like to add a $5.00 charge whenever the txtBwayEDUGift checkbox is selected. The javascript code I currently have is reducing the amount when checkbox is unchecked, but not applying the charge when selected. I can provide additonal code if needed.
Here is my input type from my aspx page:
<input type="checkbox" name="txtBwayEDUGift" id="txtBwayEDUGift" onchange="checkboxAdd(this);" checked="checked" />
Here is my javascript:
{
var divPrevAmt;
if (type == 0)
{
divPrevAmt = document.getElementById("divBwayGiftPrevAmt");
}
else if (type == 1)
{
divPrevAmt = document.getElementById("divBwayEDUGiftPrevPmt");
}
var txtAmt = document.getElementById(obj);
var amt = txtAmt.value;
amt = amt.toString().replace("$","");
amt = amt.replace(",","");
var prevAmt = divPrevAmt.innerHTML;
try
{
amt = amt * 1;
}
catch(err)
{
txtAmt.value = "";
return;
}
if (amt >= 0) //get the previous amount if any
{
if (type == 0)
{
if (prevAmt.toString().length > 0)
{
prevAmt = prevAmt * 1;
}
else
{
prevAmt = 0;
}
}
else if (type == 1)
{
if (prevAmt.toString().length > 0)
{
prevAmt = prevAmt * 1;
}
else
{
prevAmt = 0;
}
}
//now update the master total
var total = document.getElementById("txtTotal");
var dTotal = total.value.toString().replace("$","");
dTotal = dTotal.replace(",","");
dTotal = dTotal * 1;
var newTotal = dTotal - prevAmt;
newTotal = newTotal + amt;
divPrevAmt.innerHTML = amt.toString();
newTotal = addCommas(newTotal);
amt = addCommas(amt);
txtAmt.value = "$" + amt;
total.value = "$" + newTotal;
}
else
{
txtAmt.value = "";
return;
}
}
function disable()
{
var txtTotal = document.getElementById("txtTotal");
var txt = txtTotal.value;
txtTotal.value = txt;
var BwayGift = document.getElementById("txtBwayGift");
BwayGift.focus();
}
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
var newTotal = x1 + x2;
if (newTotal.toString().indexOf(".") != -1)
{
newTotal = newTotal.substring(0,newTotal.indexOf(".") + 3);
}
return newTotal;
}
function checkChanged()
{
var cb = document.getElementById("cbOperaGala");
if (cb.checked == true)
{
var tableRow = document.getElementById("trCheckbox");
tableRow.style.backgroundImage = "url('images/otTableRowSelect.jpg')";
}
else if (cb.checked == false)
{
var tableRow = document.getElementById("trCheckbox");
tableRow.style.backgroundImage = "";
}
}
function alertIf()
{
var i = 0;
for (i=5;i<=10;i++)
{
try{
var subtotal2 = document.getElementById("txtSubTotal" + i);
var dSubtotal2 = subtotal2.value;
dSubtotal2 = dSubtotal2.replace("$","");
dSubtotal2 = dSubtotal2 * 1;}
catch (Error){dSubtotal2 = 0}
if (dSubtotal2 > 0)
{
alert("You have selected the I want it all package, \n however you have also selected individual tickets to the same events. \n If you meant to do this, please disregard this message.");
break;
}
}
}
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
//Add $5.00 donation to cart
function checkboxAdd(ctl) {
if (ctl.checked == true) {
// alert("adding $5");
calculateTotal(5, "A");
} else {
// alert("deducting $5");
calculateTotal( 5, "S");
}
}
</script>
I do not understand the context of the scenario. When a user clicks the checkbox are you making an HTTP request to the server? Or is this a simple form POST page? What is calculateTotal() doing?
I figured it out. So the functionality I had in place was fine.
//Add $5.00 donation to cart
function checkboxAdd(txtBwayEDUGift) {
if (txtBwayEDUGift.checked == true) {
// alert("adding $5");
calculateTotal(5, "A");
} else {
// alert("deducting $5");
calculateTotal(5, "S");
}
}
But I needed to add a load function:
function load() {
calculateTotal(5, "A");
}
<body onload="load()">
Along with adding a reference to my c# page:
if (txtBwayEDUGift.Checked)
{
addDonations(5.00, 93);
}
You can use jQuery :)
$(txtBwayEDUGift).change(calculateTotal(5, "S"));