Conditional drop down is not working in IE - javascript

I created a filtering drop downs on hover, where by selecting the country name on hover from the first drop down the respective destinations will appear in the second drop down on hover. But It is not working in internet explorer & also in edge why?
function changeddl(obj) {
var text = obj.options[obj.selectedIndex].text;
var ddl2 = document.querySelectorAll('#iOperation option');
for (var i = 1; i < ddl2.length; i++) {
var option = ddl2[i];
option.style.display = 'none';
if (text == 'Pick a Country') {
if (['Pick a Destination'].indexOf(option.text) > -1)
option.style.display = 'none'
}
if (text == 'India') {
if (['Bangalore', 'Delhi', 'Pune','Gujarat','Rajastan','Goa','Haryana','Kerela','Hampi'].indexOf(option.text) > -1)
option.style.display = 'block'
}
if (text == 'Sri Lanka') {
if (['colombio','fetero','Kandy','Galle','Nuwara','Negombo'].indexOf(option.text) > -1)
option.style.display = 'block'
}
if (text == 'Swedan') {
if (['Swedan'].indexOf(option.text) > -1)
option.style.display = 'block'
}
}
}
function DropList() {
var n = document.getElementById("iFunction").options.length;
document.getElementById("iFunction").size = n;
}
function handleSelect(elm){
window.location = elm.value;
}
var countryArrays = [ ['Bangalore', 'Delhi','Pune','Gujarat','Rajastan','Goa','Haryana','Kerela','Hampi'],
['colombio','fetero','Kandy','Galle','Nuwara','Negombo'],['Swedan'] ];
function DropNew() {
var index = document.getElementById("iFunction").selectedIndex - 1;
if (index >= 0){
document.getElementById("iOperation").size = countryArrays[index].length + 1;
} else {
jQuery("#popup").show();
}
}
function hidePopup() {
jQuery("#popup").hide();
}
function handleSelect(elm){
window.location = elm.value;
}

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>

Javascript injection add item to basket

I am trying to run this script which effectively goes through a json list that contains url and a size to go to the link set add the item to cart based on size, check if it is in stock or already added. I have got the link and the size searching algorithms work independently but together they seem to not work and I can't figure out why?
var foundall = false;
var copItems = [{
"url": "https://www.supremenewyork.com/mobile/#products/303518/22745",
"size": "Medium"
}];
for (var i = 0; i < copItems.length; i++) {
AddToCart(copItems[i], function(carted) {
console.log(carted);
});
}
function AddToCart(item, callback) {
location.href = item.url;
var counter = 0;
var waitToAppear = setInterval(function() {
if (document.querySelector('#cart-update > span')) {
if (document.querySelector('#cart-update > span').innerHTML == 'remove') {
return callback("failed");
clearInterval(waitToAppear);
} else if (document.querySelector('#cart-update > span').innerHTML == 'sold out') {
copSelectSize(size, function(data) {
return callback(data);
clearInterval(waitToAppear);
});
} else if (document.querySelector('#cart-update > span').innerHTML == 'add to basket') {
copSelectSize(item.size, function(Sized) {
return callback("failed");
clearInterval(waitToAppear);
})
} else {
counter += 1;
if (counter == 5) {
return callback("failed");
clearInterval(waitToAppear);
}
}
}
}, 100);
}
function copSelectSize(size, callback) {
var counter = 0;
var checkExist = setInterval(function() {
if (document.getElementById('size-options').length) {
var sizes = document.getElementById('size-options').options;
var size_id;
for (var i = 0; i < sizes.length; i++) {
if (sizes[i].innerText == '\(Size)') {
size_id = i;
document.getElementById('size-options').selectedIndex = size_id;
document.getElementById('size-options-link').innerHTML = '\(Size)';
if (document.querySelector('#cart-update > span').innerHTML != 'remove') {
document.querySelector('#cart-update > span').click();
return callback("success");
clearInterval(checkExist);
}
var checkExista = setInterval(function() {
if (document.querySelector('#cart-update > span').innerHTML == 'remove') {
checkExista = '';
}
clearInterval(checkExista);
}, 100);
break;
}
}
}
counter += 1;
if (counter == 5) {
return callback("failed");
clearInterval(checkExist);
}
}, 200);
}

DOMParser - children are not DOM objects

There is a strange behavior with DOMParser. When I use "text/xml" as the parameter I get my object and each time I use a child (like parentNodes), the child is itself a DOM object. However, when I use "text/html" as the parameter, the children are not DOM objects. Why is that and how can I have DOM objects for all the children?
Here is what I do:
parser = new DOMParser();
doc = parser.parseFromString(stringContainingHTMLSource, "text/html").getElementsByTagName('p');
console.log(doc[0].childNodes[0]);
My childNode returns the element but not as a DOM object...
Edit:
Here are my recursive functions:
var getParents = function(node, parentNodes){
if(node.nodeName == 'span'){
parentNodes.push(node.attributes[0].nodeValue);
} else if(node.nodeName == 'p' && node.attributes.length > 0) {
parentNodes.push(node.nodeName);
parentNodes.push(node.attributes[0].nodeValue);
} else {
parentNodes.push(node.nodeName);
}
if(node.parentNode.nodeName != '#document'){
getParents(node.parentNode, parentNodes);
}
return parentNodes;
};
var parse = function(node, vertical, horizontal, paragraph){
if(node.childNodes.length > 0){
for(var int = 0; int < node.childNodes.length; int++){
parse(node.childNodes[int], vertical, horizontal, paragraph);
}
} else{
var object = {};
var attributes = getParents(node, []);
for(var int = 0; int < attributes.length; int++) {
// right alignment
if(/text-align/i.test(attributes[int])){
object.alignment = attributes[int].split(": ")[1].replace(';','');
} else if (/color/i.test(attributes[int])) {
// color
object.color = attributes[int].split(":")[1];
} else if (attributes[int] == 'em') {
// italic
if (object.italics) {
delete object.bold;
object.bolditalics = true;
} else {
object.italics = true;
}
} else if (attributes[int] == 'strong') {
// bold
if (object.italics) {
delete object.italics;
object.bolditalics = true;
} else {
object.bold = true;
}
} else if (attributes[int] == 'u') {
// underline
object.decoration = 'underline';
} else if (attributes[int] == 's') {
// strike
object.decoration = 'lineThrough';
}
}
object.text = node.textContent;
pdfContent[vertical][horizontal].push(object);
}
};
for(var vertical = 0; vertical < payment.htmlContent.length; vertical++) {
for(var horizontal = 0; horizontal < payment.htmlContent[vertical].length; horizontal++) {
var parser = new DOMParser();
var paragraphs = parser.parseFromString(payment.htmlContent[vertical][horizontal], "text/xml").getElementsByTagName('p');
for (var paragraph = 0; paragraph < paragraphs.length; paragraph++) {
for (var num = 0; num < paragraphs[paragraph].childNodes.length; num++) {
parse(paragraphs[paragraph].childNodes[num], vertical, horizontal, paragraph);
}
}
}
}
I made a few assumptions on what the values are and after I Added a few verifications like if(node.attributes.length>0)into your code, it seems to work.
var payment={htmlContent:[['<p>some<em>text</em></p>', '<p>some<span>text<strong>here</strong></span></p>'],['<p>some<s>text</s></p>', '<p>some<span style="color:#FF00FF">text</span></p>']]};
var getParents = function(node, parentNodes){
if(node.nodeName == 'span'){
if(node.attributes.length>0)
parentNodes.push(node.attributes[0].nodeValue);
} else if(node.nodeName == 'p' && node.attributes.length > 0) {
parentNodes.push(node.nodeName);
if(node.attributes.length>0)
parentNodes.push(node.attributes[0].nodeValue);
} else {
parentNodes.push(node.nodeName);
}
if(node.parentNode.nodeName != '#document'){
getParents(node.parentNode, parentNodes);
}
return parentNodes;
};
var parse = function(node, vertical, horizontal, paragraph){
if(node.childNodes.length > 0){
for(var int = 0; int < node.childNodes.length; int++){
parse(node.childNodes[int], vertical, horizontal, paragraph);
}
} else{
var object = {};
var attributes = getParents(node, []);
console.log(attributes);
for(var int = 0; int < attributes.length; int++) {
// right alignment
if(/text-align/i.test(attributes[int])){
object.alignment = attributes[int].split(": ")[1].replace(';','');
} else if (/color/i.test(attributes[int])) {
// color
object.color = attributes[int].split(":")[1];
} else if (attributes[int] == 'em') {
// italic
if (object.italics) {
delete object.bold;
object.bolditalics = true;
} else {
object.italics = true;
}
} else if (attributes[int] == 'strong') {
// bold
if (object.italics) {
delete object.italics;
object.bolditalics = true;
} else {
object.bold = true;
}
} else if (attributes[int] == 'u') {
// underline
object.decoration = 'underline';
} else if (attributes[int] == 's') {
// strike
object.decoration = 'lineThrough';
}
}
object.text = node.textContent;
if(!pdfContent[vertical])pdfContent[vertical]=[];
if(!pdfContent[vertical][horizontal])
pdfContent[vertical][horizontal]=[];
pdfContent[vertical][horizontal].push(object);
}
};
var pdfContent = [];
for(var vertical = 0; vertical < payment.htmlContent.length; vertical++) {
for(var horizontal = 0; horizontal < payment.htmlContent[vertical].length; horizontal++) {
var parser = new DOMParser();
var paragraphs = parser.parseFromString(payment.htmlContent[vertical][horizontal], "text/xml").getElementsByTagName('p');
for (var paragraph = 0; paragraph < paragraphs.length; paragraph++) {
for (var num = 0; num < paragraphs[paragraph].childNodes.length; num++) {
parse(paragraphs[paragraph].childNodes[num], vertical, horizontal, paragraph);
}
}
}
}
for(var i=0; i<pdfContent.length; i++){
for(var j=0; j<pdfContent[i].length; j++){
document.querySelector('#log').textContent+=pdfContent[i][j].toSource();
}
}
<p id="log"></p>

JavaScript Query on Optionset

How can I save the remaining optionset items after removing an item from the list? Is there any other way of adding the removed option from an optionset in XRM?
function func1() {
var A1 = Xrm.Page.getAttribute("attribute1").getValue();
var B1 = Xrm.Page.getAttribute("attribute2").getValue();
var PickListA1 = Xrm.Page.getControl("attribute1");
var PickListA1Options = PickListA1.getAttribute().getOptions();
var j = 0;
if (B1 == "3") {
if (A1 == "1") {
PickListA1.clearOptions();
for (var i in PickListA1Options) {
if (PickListA1Options[i].value != "null") {
PickListA1.addOption(PickListA1Options[i]);
}
}
}
PickListA1.removeOption(1);
}
else {
PickListA1.getAttribute().setvalue(A1);
for (var i in PickListA1Options) {
if (PickListA1Options[i].value == "1") {
break;
}
else {
j++;
}
}
if (j > 1) {
PickListA1.addOption(PickListA1Options[1]);
}
}
}

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

Categories