Edit ajax loaded content - javascript

I have a HTML that loads a table from another page. I've got the CSS to work properly, but I can't edit the table using jQuery when it's pooled by the script, only when I have the table directly on the page. I'm guessing that maybe my changes are running before the load? I don't know..
I want to let you know that I'm not a programmer my self, but more of a curious person. I've searched around and found some things, but the lack of knowledge doesn't let me implement them. Hope you can help me.
The Script I use to read the data from the other page (p1.html)
<script type="text/javascript">
var TimerLoad, TimerChange;
var MaxNum, Rafraichir, Changement, ClassementReduit, ClassementReduitXpremier;
var UrlRefresh, UrlChange;
Rafraichir = 30000;
Changement = 150000;
MaxNum = 1;
ClassementReduit = 0;
ClassementReduitXpremier = 10;
function Load(url, target) {
var xhr;
var fct;
if (UrlChange) url = UrlRefresh;
else UrlRefresh = url;
UrlChange = 0;
if (TimerLoad) clearTimeout(TimerLoad);
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
} catch (e2) {
try {
xhr = new XMLHttpRequest
} catch (e3) {
xhr = false
}
}
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200)
if (ClassementReduit == 0) document.getElementById(target).innerHTML = xhr.responseText;
else document.getElementById(target).innerHTML = ExtraireClassementReduit(xhr.responseText)
};
xhr.open("GET", url + "?r=" + Math.random(), true);
xhr.send(null);
fct = function() {
Load(url, target)
};
TimerLoad = setTimeout(fct, Rafraichir)
}
function ExtraireClassementReduit(Texte) {
var i, j, CompteurTD, CompteurTR;
var ColPosition, ColNumero, ColNom, ColEcart1er;
var Lignes;
var NouveauTexte;
CompteurTR = 0;
ColPosition = -1;
ColNumero = -1;
ColNom = -1;
ColEcart1er = -1;
Texte = Texte.substring(Texte.indexOf("<tr"));
Lignes = Texte.split("\r\n");
NouveauTexte = '<table width="100%" cellpadding="0" cellspacing="0">';
for (i = 0; i < Lignes.length; i++)
if (Lignes[i].substring(0, 3) == "<tr") {
NouveauTexte += Lignes[i];
CompteurTD = 0
} else if (Lignes[i].substring(0, 4) == "</tr") {
CompteurTR++;
if (CompteurTR == ClassementReduitXpremier + 1) break
} else if (Lignes[i].substring(0, 3) == "<td") {
if (CompteurTR == 0)
if (Lignes[i].indexOf("\"Id_Position\"") != -1) {
ColPosition = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
} else if (Lignes[i].indexOf("\"Id_Numero\"") != -1) {
ColNumero = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
} else if (Lignes[i].indexOf("\"Id_Nom\"") != -1) {
ColNom = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
} else {
if (Lignes[i].indexOf("\"Id_Ecart1er\"") != -1) {
ColEcart1er = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
}
} else if (CompteurTD == ColPosition || CompteurTD == ColNumero || CompteurTD == ColNom || CompteurTD == ColEcart1er) NouveauTexte += Lignes[i];
CompteurTD++
}
NouveauTexte += "</table>";
return NouveauTexte
}
function Change() {
var Num, Index;
if (document.forms["Changement"].chkChangement.checked) {
Index = UrlRefresh.indexOf(".");
Num = parseInt(UrlRefresh.substring(1, Index)) + 1;
if (Num > MaxNum) Num = 1;
UrlRefresh = "p" + Num + ".html";
UrlChange = 1;
fct = function() {
Change()
};
TimerChange = setTimeout(fct, Changement)
} else if (TimerChange) clearTimeout(TimerChange)
};
</script>
Loading the table into the body
$(document).ready(Load('p1.html', 'result'));
The code I need to run after (it works with the table directly on page or even on a button, but I can't get to work on page load)
function show_hide_column(col_id, do_show) {
var stl;
if (do_show) stl = 'block'
else stl = 'none';
var tbl = document.getElementsByTagName('table')[0];
var index = document.getElementById(col_id).cellIndex;
var rows = tbl.getElementsByTagName('tr');
for (var row = 0; row < rows.length; row++) {
var cels = rows[row].getElementsByTagName('td')
cels[index].style.display = stl;
}
}
function hide() {
show_hide_column("Id_Position", false);
show_hide_column("Id_Equipe", false);
show_hide_column("Id_Vehicule", false);
}

I fired a console.log() message for every stage of the previous code, to know when exactly the table was added to the page, to then hide the columns. Got it to work.

Related

table pagination in pure javascript but if number is not working properly?

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>

Using w3data.js and want to remove outside 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);
}
}

Javascript Expandable Header not working correctly

I am using a piece of Javascript that enables the user to expand a h3 tag in my HTML document. It is working perfectly however when I refresh my page the first time the header is contracted and then when I refresh it a second time the header is expanded again.
I would like it to just stay expanded and not contract ever but I am unsure what changes I may need to make to the code:
I should point out that when the user visits the page for the first time the header is already expanded. I do that by calling the function from within the body tag.
<body onLoad="expandcontent('sc1')">
This is the code:
var enablepersist = "on" //Enable saving state of content structure using session cookies? (on/off)
var collapseprevious = "yes" //Collapse previously open content when opening present? (yes/no)
if (document.getElementById) {
document.write('<style type="text/css">')
document.write('.switchcontent{display:none;}')
document.write('</style>')
}
function getElementbyClass(classname) {
ccollect = new Array()
var inc = 0
var alltags = document.all ? document.all : document.getElementsByTagName("*")
for (i = 0; i < alltags.length; i++) {
if (alltags[i].className == classname)
ccollect[inc++] = alltags[i]
}
}
function contractcontent(omit) {
var inc = 0
while (ccollect[inc]) {
if (ccollect[inc].id != omit)
ccollect[inc].style.display = "none"
inc++
}
}
function expandcontent(cid) {
if (typeof ccollect != "undefined") {
if (collapseprevious == "yes")
contractcontent(cid)
document.getElementById(cid).style.display = (document.getElementById(cid).style.display != "block") ? "block" : "none"
}
}
function revivecontent() {
contractcontent("omitnothing")
selectedItem = getselectedItem()
selectedComponents = selectedItem.split("|")
for (i = 0; i < selectedComponents.length - 1; i++)
document.getElementById(selectedComponents[i]).style.display = "block"
}
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue = unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function getselectedItem() {
if (get_cookie(window.location.pathname) != "") {
selectedItem = get_cookie(window.location.pathname)
return selectedItem
} else
return ""
}
function saveswitchstate() {
var inc = 0,
selectedItem = ""
while (ccollect[inc]) {
if (ccollect[inc].style.display == "block")
selectedItem += ccollect[inc].id + "|"
inc++
}
document.cookie = window.location.pathname + "=" + selectedItem
}
function do_onload() {
uniqueidn = window.location.pathname + "firsttimeload"
getElementbyClass("switchcontent")
if (enablepersist == "on" && typeof ccollect != "undefined") {
document.cookie = (get_cookie(uniqueidn) == "") ? uniqueidn + "=1" : uniqueidn + "=0"
firsttimeload = (get_cookie(uniqueidn) == 1) ? 1 : 0 //check if this is 1st page load
if (!firsttimeload)
revivecontent()
}
}
if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload = do_onload
if (enablepersist == "on" && document.getElementById)
window.onunload = saveswitchstate

Adding price to total when checkbox is selected

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"));

Why will my Javascript not run in IE

Below is my code. It is supposed to filter a table. It functions great in everything but IE. Can you help?
Perhaps there is a missing tag or something. I've been over it a number of times and could really do with someone's help please!
<script type="text/javascript">
function hasPath(element, cls) {
return (' ' + element.getAttribute('pathway')).indexOf(cls) > -1;
}
function hasLevel(element, cls) {
return (' ' + element.getAttribute('level')).indexOf(cls) > -1;
}
function hasBody(element, cls) {
return (' ' + element.getAttribute('body')).indexOf(cls) > -1;
}
function QualificationSearch() {
var imgdiv = document.getElementById("Chosen_Pathway_img");
var p = document.getElementById("PathwaySelect");
var pathway = p.options[p.selectedIndex].value;
if (pathway == "ALLPATHS") {
pathway = "";
imgdiv.src = "/templates/superb/images/QualChecker/pic_0.png"
}
if (pathway == "ES") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_1.png"
}
if (pathway == "HOUSING") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_2.png"
}
if (pathway == "PLAYWORK") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_3.png"
}
if (pathway == "SC") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_4.png"
}
if (pathway == "YW") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_5.png"
}
var a = document.getElementById("AwardingBodySelect");
var awardingBody = a.options[a.selectedIndex].value;
if (awardingBody == "ALLBODIES") {
awardingBody = "";
}
var levelGroup = document.getElementsByName("LevelGroup");
var chosenLevel = ""
for (var g = 0; g < levelGroup.length; g++) {
if (levelGroup[g].checked) {
chosenLevel += levelGroup[g].value + " ";
}
}
if (chosenLevel == undefined) {
var chosenLevel = "";
} else {
var splitLevel = chosenLevel.split(" ");
var levelA = splitLevel[0];
var levelB = splitLevel[1];
var levelC = splitLevel[2];
var levelD = splitLevel[3];
if (levelA == "") {
levelA = "NOLVL"
}
if (levelB == "") {
levelB = "NOLVL"
}
if (levelC == "") {
levelC = "NOLVL"
}
if (levelD == "") {
levelD = "NOLVL"
}
}
var fil = document.getElementsByName("QList");
for (var i = 0; i < fil.length; i++) {
fil.item(i).style.display = "none";
if ((hasBody(fil.item(i), awardingBody) == true || awardingBody == "") && (hasPath(fil.item(i), pathway) == true || pathway == "") && ((hasLevel(fil.item(i), levelA) == true || hasLevel(fil.item(i), levelB) == true || hasLevel(fil.item(i), levelC) == true || hasLevel(fil.item(i), levelD) == true) || chosenLevel == "")) {
fil.item(i).style.display = "block";
}
}
}
</script>
Check your semicolons. IE is far more strict on that kind of stuff than FF.

Categories