How to fixed the header of the table in the page? - codeigniter

This is my view page:
In this page when the scroll the entire page in chrome the header of the table should be fixed only content should be scrolled.I have searched many codes in google but it not working.
My table code:
<table id="customers" >
<thead>
<tr>
<th>MillCode</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php foreach ($query as $row): ?>
<tr>
<td><a href="<?=site_url('Sales/Sales_Edit/'.$row['millcode'])?>"><?=$row['mname']?></td>
<td dir="rtl"><a href="<?=site_url('Sales/Sales_Edit/'.$row['millcode'])?>"><?php echo number_format($row['amount']);?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
Please help to solve this problem.

Wrap your table under a div <div class="table-wrapper"></div> and apply this css.
div.table-wrapper {
border: 1px solid #ccc;
height: 100px;
width: 100%;
overflow-y: auto;
}
table,thead,tr,th {
text-align: left;
position: sticky;
top: 0px;
background-color: #666;
color: #fff;
}

try this
HTML:
<table class="fixed-header" border="1">
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
<th>Col 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1.0</td>
<td>Row 1.1</td>
<td>Row 1.2</td>
<td>Row 1.3</td>
<td>Row 1.4</td>
</tr>
<tr>
<td>Row 2.0</td>
<td>Row 2.1</td>
<td>Row 2.2</td>
<td>Row 2.3</td>
<td>Row 2.4</td>
</tr>
<tr>
<td>Row 3.0</td>
<td>Row 3.1</td>
<td>Row 3.2</td>
<td>Row 3.3</td>
<td>Row 3.4</td>
</tr>
<tr>
<td>Row 4.0</td>
<td>Row 4.1</td>
<td>Row 4.2</td>
<td>Row 4.3</td>
<td>Row 4.4</td>
</tr>
<tr>
<td>Row 5.0</td>
<td>Row 5.1</td>
<td>Row 5.2</td>
<td>Row 5.3</td>
<td>Row 5.4</td>
</tr>
<tr>
<td>Row 6.0</td>
<td>Row 6.1</td>
<td>Row 6.2</td>
<td>Row 6.3</td>
<td>Row 6.4</td>
</tr>
<tr>
<td>Row 7.0</td>
<td>Row 7.1</td>
<td>Row 7.2</td>
<td>Row 7.3</td>
<td>Row 7.4</td>
</tr>
</tbody>
</table>
CSS:
.fixed-header{
width: 400px;
table-layout: fixed;
border-collapse: collapse;
}
.fixed-header tbody{
display:block;
width: 100%;
overflow: auto;
height: 100px;
}
.fixed-header thead tr {
display: block;
}
.fixed-header th, .fixed-header td {
padding: 5px;
text-align: left;
width: 200px;
}
find the demo: https://jsfiddle.net/tzk9d5s7/1/

You can stick header using javaScript
**HTML**
<!-- Begin page content -->
<div class="container">
<div class="page-header">
<h1>Sticky Table Headers</h1>
</div>
<table class="table table-striped sticky-header">
<thead>
<tr>
<th>#</th>
<th>New Table</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
</tbody>
</table>
</div>
CSS
body {
padding-top:50px;
}
table.floatThead-table {
border-top: none;
border-bottom: none;
background-color: #fff;
}
JS
// #preserve jQuery.floatThead 1.2.9 - http://mkoryak.github.io/floatThead/ - Copyright (c) 2012 - 2014 Misha Koryak
// #license MIT
! function (a) {
function b(a, b, c) {
if (8 == g) {
var d = j.width(),
e = f.debounce(function () {
var a = j.width();
d != a && (d = a, c())
}, a);
j.on(b, e)
} else j.on(b, f.debounce(c, a))
}
function c(a) {
window.console && window.console && window.console.log && window.console.log(a)
}
function d() {
var b = a('<div style="width:50px;height:50px;overflow-y:scroll;position:absolute;top:-200px;left:-200px;"><div style="height:100px;width:100%"></div>');
a("body").append(b);
var c = b.innerWidth(),
d = a("div", b).innerWidth();
return b.remove(), c - d
}
function e(a) {
if (a.dataTableSettings) for (var b = 0; b < a.dataTableSettings.length; b++) {
var c = a.dataTableSettings[b].nTable;
if (a[0] == c) return !0
}
return !1
}
a.floatThead = a.floatThead || {}, a.floatThead.defaults = {
cellTag: null,
headerCellSelector: "tr:first>th:visible",
zIndex: 1001,
debounceResizeMs: 10,
useAbsolutePositioning: !0,
scrollingTop: 0,
scrollingBottom: 0,
scrollContainer: function () {
return a([])
},
getSizingRow: function (a) {
return a.find("tbody tr:visible:first>*")
},
floatTableClass: "floatThead-table",
floatWrapperClass: "floatThead-wrapper",
floatContainerClass: "floatThead-container",
copyTableClass: !0,
debug: !1
};
var f = window._,
g = function () {
for (var a = 3, b = document.createElement("b"), c = b.all || []; a = 1 + a, b.innerHTML = "<\!--[if gt IE " + a + "]><i><![endif]-->", c[0];);
return a > 4 ? a : document.documentMode
}(),
h = null,
i = function () {
if (g) return !1;
var b = a("<table><colgroup><col></colgroup><tbody><tr><td style='width:10px'></td></tbody></table>");
a("body").append(b);
var c = b.find("col").width();
return b.remove(), 0 == c
}, j = a(window),
k = 0;
a.fn.floatThead = function (l) {
if (l = l || {}, !f && (f = window._ || a.floatThead._, !f)) throw new Error("jquery.floatThead-slim.js requires underscore. You should use the non-lite version since you do not have underscore.");
if (8 > g) return this;
if (null == h && (h = i(), h && (document.createElement("fthtr"), document.createElement("fthtd"), document.createElement("fthfoot"))), f.isString(l)) {
var m = l,
n = this;
return this.filter("table").each(function () {
var b = a(this).data("floatThead-attached");
if (b && f.isFunction(b[m])) {
var c = b[m]();
"undefined" != typeof c && (n = c)
}
}), n
}
var o = a.extend({}, a.floatThead.defaults || {}, l);
return a.each(l, function (b) {
b in a.floatThead.defaults || !o.debug || c("jQuery.floatThead: used [" + b + "] key to init plugin, but that param is not an option for the plugin. Valid options are: " + f.keys(a.floatThead.defaults).join(", "))
}), this.filter(":not(." + o.floatTableClass + ")").each(function () {
function c(a) {
return a + ".fth-" + y + ".floatTHead"
}
function i() {
var b = 0;
A.find("tr:visible").each(function () {
b += a(this).outerHeight(!0)
}), Z.outerHeight(b), $.outerHeight(b)
}
function l() {
var a = z.outerWidth(),
b = I.width() || a;
if (X.width(b - F.vertical), O) {
var c = 100 * a / (b - F.vertical);
S.css("width", c + "%")
} else S.outerWidth(a)
}
function m() {
C = (f.isFunction(o.scrollingTop) ? o.scrollingTop(z) : o.scrollingTop) || 0, D = (f.isFunction(o.scrollingBottom) ? o.scrollingBottom(z) : o.scrollingBottom) || 0
}
function n() {
var b, c;
if (V) b = U.find("col").length;
else {
var d;
d = null == o.cellTag && o.headerCellSelector ? o.headerCellSelector : "tr:first>" + o.cellTag, c = A.find(d), b = 0, c.each(function () {
b += parseInt(a(this).attr("colspan") || 1, 10)
})
}
if (b != H) {
H = b;
for (var e = [], f = [], g = [], i = 0; b > i; i++) e.push('<th class="floatThead-col"/>'), f.push("<col/>"), g.push("<fthtd style='display:table-cell;height:0;width:auto;'/>");
f = f.join(""), e = e.join(""), h && (g = g.join(""), W.html(g), bb = W.find("fthtd")), Z.html(e), $ = Z.find("th"), V || U.html(f), _ = U.find("col"), T.html(f), ab = T.find("col")
}
return b
}
function p() {
if (!E) {
if (E = !0, J) {
var a = z.width(),
b = Q.width();
a > b && z.css("minWidth", a)
}
z.css(db), S.css(db), S.append(A), B.before(Y), i()
}
}
function q() {
E && (E = !1, J && z.width(fb), Y.detach(), z.prepend(A), z.css(eb), S.css(eb))
}
function r(a) {
J != a && (J = a, X.css({
position: J ? "absolute" : "fixed"
}))
}
function s(a, b, c, d) {
return h ? c : d ? o.getSizingRow(a, b, c) : b
}
function t() {
var a, b = n();
return function () {
var c = s(z, _, bb, g);
if (c.length == b && b > 0) {
if (!V) for (a = 0; b > a; a++) _.eq(a).css("width", "");
q();
var d = [];
for (a = 0; b > a; a++) d[a] = c.get(a).offsetWidth;
for (a = 0; b > a; a++) ab.eq(a).width(d[a]), _.eq(a).width(d[a]);
p()
} else S.append(A), z.css(eb), S.css(eb), i()
}
}
function u(a) {
var b = I.css("border-" + a + "-width"),
c = 0;
return b && ~b.indexOf("px") && (c = parseInt(b, 10)), c
}
function v() {
var a, b = I.scrollTop(),
c = 0,
d = L ? K.outerHeight(!0) : 0,
e = M ? d : -d,
f = X.height(),
g = z.offset(),
i = 0;
if (O) {
var k = I.offset();
c = g.top - k.top + b, L && M && (c += d), c -= u("top"), i = u("left")
} else a = g.top - C - f + D + F.horizontal;
var l = j.scrollTop(),
m = j.scrollLeft(),
n = I.scrollLeft();
return b = I.scrollTop(),
function (k) {
if ("windowScroll" == k ? (l = j.scrollTop(), m = j.scrollLeft()) : "containerScroll" == k ? (b = I.scrollTop(), n = I.scrollLeft()) : "init" != k && (l = j.scrollTop(), m = j.scrollLeft(), b = I.scrollTop(), n = I.scrollLeft()), !h || !(0 > l || 0 > m)) {
if (R) r("windowScrollDone" == k ? !0 : !1);
else if ("windowScrollDone" == k) return null;
g = z.offset(), L && M && (g.top += d);
var o, s, t = z.outerHeight();
if (O && J) {
if (c >= b) {
var u = c - b;
o = u > 0 ? u : 0
} else o = P ? 0 : b;
s = i
} else !O && J ? (l > a + t + e ? o = t - f + e : g.top > l + C ? (o = 0, q()) : (o = C + l - g.top + c + (M ? d : 0), p()), s = 0) : O && !J ? (c > b || b - c > t ? (o = g.top - l, q()) : (o = g.top + b - l - c, p()), s = g.left + n - m) : O || J || (l > a + t + e ? o = t + C - l + a + e : g.top > l + C ? (o = g.top - l, p()) : o = C, s = g.left - m);
return {
top: o,
left: s
}
}
}
}
function w() {
var a = null,
b = null,
c = null;
return function (d, e, f) {
null == d || a == d.top && b == d.left || (X.css({
top: d.top,
left: d.left
}), a = d.top, b = d.left), e && l(), f && i();
var g = I.scrollLeft();
J && c == g || (X.scrollLeft(g), c = g)
}
}
function x() {
if (I.length) {
var a = I.width(),
b = I.height(),
c = z.height(),
d = z.width(),
e = d > a ? G : 0,
f = c > b ? G : 0;
F.horizontal = d > a - f ? G : 0, F.vertical = c > b - e ? G : 0
}
}
var y = k,
z = a(this);
if (z.data("floatThead-attached")) return !0;
if (!z.is("table")) throw new Error('jQuery.floatThead must be run on a table element. ex: $("table").floatThead();');
var A = z.find("thead:first"),
B = z.find("tbody:first");
if (0 == A.length) throw new Error("jQuery.floatThead must be run on a table that contains a <thead> element");
var C, D, E = !1,
F = {
vertical: 0,
horizontal: 0
}, G = d(),
H = 0,
I = o.scrollContainer(z) || a([]),
J = o.useAbsolutePositioning;
null == J && (J = o.scrollContainer(z).length);
var K = z.find("caption"),
L = 1 == K.length;
if (L) var M = "top" === (K.css("caption-side") || K.attr("align") || "top");
var N = a('<fthfoot style="display:table-footer-group;"/>'),
O = I.length > 0,
P = !1,
Q = a([]),
R = 9 >= g && !O && J,
S = a("<table/>"),
T = a("<colgroup/>"),
U = z.find("colgroup:first"),
V = !0;
0 == U.length && (U = a("<colgroup/>"), V = !1);
var W = a('<fthrow style="display:table-row;height:0;"/>'),
X = a('<div style="overflow: hidden;"></div>'),
Y = a("<thead/>"),
Z = a('<tr class="size-row"/>'),
$ = a([]),
_ = a([]),
ab = a([]),
bb = a([]);
if (Y.append(Z), z.prepend(U), h && (N.append(W), z.append(N)), S.append(T), X.append(S), o.copyTableClass && S.attr("class", z.attr("class")), S.attr({
cellpadding: z.attr("cellpadding"),
cellspacing: z.attr("cellspacing"),
border: z.attr("border")
}), S.css({
borderCollapse: z.css("borderCollapse"),
border: z.css("border")
}), S.addClass(o.floatTableClass).css("margin", 0), J) {
var cb = function (a, b) {
var c = a.css("position"),
d = "relative" == c || "absolute" == c;
if (!d || b) {
var e = {
paddingLeft: a.css("paddingLeft"),
paddingRight: a.css("paddingRight")
};
X.css(e), a = a.wrap("<div class='" + o.floatWrapperClass + "' style='position: relative; clear:both;'></div>").parent(), P = !0
}
return a
};
O ? (Q = cb(I, !0), Q.append(X)) : (Q = cb(z), z.after(X))
} else z.after(X);
X.css({
position: J ? "absolute" : "fixed",
marginTop: 0,
top: J ? 0 : "auto",
zIndex: o.zIndex
}), X.addClass(o.floatContainerClass), m();
var db = {
"table-layout": "fixed"
}, eb = {
"table-layout": z.css("tableLayout") || "auto"
}, fb = z[0].style.width || "";
x();
var gb, hb = function () {
(gb = t())()
};
hb();
var ib = v(),
jb = w();
jb(ib("init"), !0);
var kb = f.debounce(function () {
jb(ib("windowScrollDone"), !1)
}, 300),
lb = function () {
jb(ib("windowScroll"), !1), kb()
}, mb = function () {
jb(ib("containerScroll"), !1)
}, nb = function () {
m(), x(), hb(), ib = v(), (jb = w())(ib("resize"), !0, !0)
}, ob = f.debounce(function () {
x(), m(), hb(), ib = v(), jb(ib("reflow"), !0)
}, 1);
O ? J ? I.on(c("scroll"), mb) : (I.on(c("scroll"), mb), j.on(c("scroll"), lb)) : j.on(c("scroll"), lb), j.on(c("load"), ob), b(o.debounceResizeMs, c("resize"), nb), z.on("reflow", ob), e(z) && z.on("filter", ob).on("sort", ob).on("page", ob), z.data("floatThead-attached", {
destroy: function () {
var a = ".fth-" + y;
q(), z.css(eb), U.remove(), h && N.remove(), Y.parent().length && Y.replaceWith(A), z.off("reflow"), I.off(a), P && (I.length ? I.unwrap() : z.unwrap()), J && z.css("minWidth", ""), X.remove(), z.data("floatThead-attached", !1), j.off(a)
},
reflow: function () {
ob()
},
setHeaderHeight: function () {
i()
},
getFloatContainer: function () {
return X
},
getRowGroups: function () {
return E ? X.find("thead").add(z.find("tbody,tfoot")) : z.find("thead,tbody,tfoot")
}
}), k++
}), this
}
}(jQuery),
function (a) {
a.floatThead = a.floatThead || {}, a.floatThead._ = window._ || function () {
var b = {}, c = Object.prototype.hasOwnProperty,
d = ["Arguments", "Function", "String", "Number", "Date", "RegExp"];
return b.has = function (a, b) {
return c.call(a, b)
}, b.keys = function (a) {
if (a !== Object(a)) throw new TypeError("Invalid object");
var c = [];
for (var d in a) b.has(a, d) && c.push(d);
return c
}, a.each(d, function () {
var a = this;
b["is" + a] = function (b) {
return Object.prototype.toString.call(b) == "[object " + a + "]"
}
}), b.debounce = function (a, b, c) {
var d, e, f, g, h;
return function () {
f = this, e = arguments, g = new Date;
var i = function () {
var j = new Date - g;
b > j ? d = setTimeout(i, b - j) : (d = null, c || (h = a.apply(f, e)))
}, j = c && !d;
return d || (d = setTimeout(i, b)), j && (h = a.apply(f, e)), h
}
}, b
}()
}(jQuery);
$(document).ready(function () {
$(".sticky-header").floatThead({
scrollingTop: 50
});
});

Related

PrismJs line numbers for code blocks inside an expandable div appear wrapped. Recover when zoomed in/out

I am trying to add line numbers to code blocks using PrismJs Line Numbers plugin.
The code blocks are included within an expanded div as shown below:
<h2><a class="dropspot" data-open-text="" data-rhwidget="ExpandSpot" data-target="expanding2" href="#">Sample </a></h2>
<div class="droptext" data-targetname="expanding2">
<p class="Codeheadingnew">Specify the inputs to create a job</p>
<div>
<pre class="line-numbers">
<code class="language-JSON">
{
"name": "Job with specific patches",
"description": "Created via API",
"approvches": [
"ca0d5b3a517",
"9285e676-61d84542c7bf"
],
</code>
</pre>
</div>
The CSS is here:
code[class*=language-],
pre[class*=language-] {
word-wrap: break-word;
color: #ccc;
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
font-size: 1em;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
line-height: 1.5;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
background-color: #35434D;
max-height: 350px;
}
pre[class*=language-] {
padding: 1em;
margin-top: -0.1em;
margin-bottom: .5em;
overflow-y: auto;
scrollbar-width: thin;
white-space: pre-wrap;
}
:not(pre)>code[class*=language-],
pre[class*=language-] {
background: #35434D;
}
:not(pre)>code[class*=language-] {
padding: .1em;
border-radius: .3em;
white-space: normal;
}
/* Code style box scrollbar for Chrome and Edge */
pre[class*=language-]::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
border-radius: 0;
background-color: inherit;
}
pre[class*=language-]::-webkit-scrollbar {
width: 8px;
background-color: #F5F5F5;
}
pre[class*=language-]::-webkit-scrollbar-thumb {
border-radius: 0;
-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
background-color: #898b8c;
}
.token.block-comment,
.token.cdata,
.token.comment,
.token.doctype,
.token.prolog {
color: #999;
}
.token.punctuation {
color: #ccc;
}
.token.attr-name,
.token.deleted,
.token.namespace,
.token.tag {
color: #e2777a;
}
.token.function-name {
color: #6196cc;
}
.token.boolean,
.token.function,
.token.number {
color: #f08d49;
}
.token.class-name,
.token.constant,
.token.property,
.token.symbol {
color: #f8c555;
}
.token.atrule,
.token.builtin,
.token.important,
.token.keyword,
.token.selector {
color: #cc99cd;
}
.token.attr-value,
.token.char,
.token.regex,
.token.string,
.token.variable {
color: #7ec699;
}
.token.entity,
.token.operator,
.token.url {
color: #67cdcc;
}
.token.bold,
.token.important {
font-weight: 700;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}
.token.inserted {
color: green;
}
pre[class*=language-].line-numbers {
position: relative;
padding-left: 3.8em;
counter-reset: linenumber;
}
pre[class*=language-].line-numbers>code {
position: relative;
white-space: pre-wrap;
}
.line-numbers .line-numbers-rows {
position: absolute;
pointer-events: none;
top: 0;
font-size: 100%;
left: -3.8em;
width: 3em;
letter-spacing: -1px;
border-right: 1px solid #999;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.line-numbers-rows>span {
display: block;
counter-increment: linenumber;
}
.line-numbers-rows>span:before {
content: counter(linenumber);
color: #999;
display: block;
padding-right: .8em;
text-align: right;
}
and the JS is here:
var _self = "undefined" != typeof window ? window : "undefined" != typeof WorkerGlobalScope && self instanceof WorkerGlobalScope ? self : {}, Prism = function (e) { var n = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i, t = 0, r = {}, a = { manual: e.Prism && e.Prism.manual, disableWorkerMessageHandler: e.Prism && e.Prism.disableWorkerMessageHandler, util: { encode: function e(n) { return n instanceof i ? new i(n.type, e(n.content), n.alias) : Array.isArray(n) ? n.map(e) : n.replace(/&/g, "&").replace(/</g, "<").replace(/\u00a0/g, " ") }, type: function (e) { return Object.prototype.toString.call(e).slice(8, -1) }, objId: function (e) { return e.__id || Object.defineProperty(e, "__id", { value: ++t }), e.__id }, clone: function e(n, t) { var r, i; switch (t = t || {}, a.util.type(n)) { case "Object": if (i = a.util.objId(n), t[i]) return t[i]; for (var l in r = {}, t[i] = r, n) n.hasOwnProperty(l) && (r[l] = e(n[l], t)); return r; case "Array": return i = a.util.objId(n), t[i] ? t[i] : (r = [], t[i] = r, n.forEach((function (n, a) { r[a] = e(n, t) })), r); default: return n } }, getLanguage: function (e) { for (; e;) { var t = n.exec(e.className); if (t) return t[1].toLowerCase(); e = e.parentElement } return "none" }, setLanguage: function (e, t) { e.className = e.className.replace(RegExp(n, "gi"), ""), e.classList.add("language-" + t) }, currentScript: function () { if ("undefined" == typeof document) return null; if ("currentScript" in document) return document.currentScript; try { throw new Error } catch (r) { var e = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(r.stack) || [])[1]; if (e) { var n = document.getElementsByTagName("script"); for (var t in n) if (n[t].src == e) return n[t] } return null } }, isActive: function (e, n, t) { for (var r = "no-" + n; e;) { var a = e.classList; if (a.contains(n)) return !0; if (a.contains(r)) return !1; e = e.parentElement } return !!t } }, languages: { plain: r, plaintext: r, text: r, txt: r, extend: function (e, n) { var t = a.util.clone(a.languages[e]); for (var r in n) t[r] = n[r]; return t }, insertBefore: function (e, n, t, r) { var i = (r = r || a.languages)[e], l = {}; for (var o in i) if (i.hasOwnProperty(o)) { if (o == n) for (var s in t) t.hasOwnProperty(s) && (l[s] = t[s]); t.hasOwnProperty(o) || (l[o] = i[o]) } var u = r[e]; return r[e] = l, a.languages.DFS(a.languages, (function (n, t) { t === u && n != e && (this[n] = l) })), l }, DFS: function e(n, t, r, i) { i = i || {}; var l = a.util.objId; for (var o in n) if (n.hasOwnProperty(o)) { t.call(n, o, n[o], r || o); var s = n[o], u = a.util.type(s); "Object" !== u || i[l(s)] ? "Array" !== u || i[l(s)] || (i[l(s)] = !0, e(s, t, o, i)) : (i[l(s)] = !0, e(s, t, null, i)) } } }, plugins: {}, highlightAll: function (e, n) { a.highlightAllUnder(document, e, n) }, highlightAllUnder: function (e, n, t) { var r = { callback: t, container: e, selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code' }; a.hooks.run("before-highlightall", r), r.elements = Array.prototype.slice.apply(r.container.querySelectorAll(r.selector)), a.hooks.run("before-all-elements-highlight", r); for (var i, l = 0; i = r.elements[l++];)a.highlightElement(i, !0 === n, r.callback) }, highlightElement: function (n, t, r) { var i = a.util.getLanguage(n), l = a.languages[i]; a.util.setLanguage(n, i); var o = n.parentElement; o && "pre" === o.nodeName.toLowerCase() && a.util.setLanguage(o, i); var s = { element: n, language: i, grammar: l, code: n.textContent }; function u(e) { s.highlightedCode = e, a.hooks.run("before-insert", s), s.element.innerHTML = s.highlightedCode, a.hooks.run("after-highlight", s), a.hooks.run("complete", s), r && r.call(s.element) } if (a.hooks.run("before-sanity-check", s), (o = s.element.parentElement) && "pre" === o.nodeName.toLowerCase() && !o.hasAttribute("tabindex") && o.setAttribute("tabindex", "0"), !s.code) return a.hooks.run("complete", s), void (r && r.call(s.element)); if (a.hooks.run("before-highlight", s), s.grammar) if (t && e.Worker) { var c = new Worker(a.filename); c.onmessage = function (e) { u(e.data) }, c.postMessage(JSON.stringify({ language: s.language, code: s.code, immediateClose: !0 })) } else u(a.highlight(s.code, s.grammar, s.language)); else u(a.util.encode(s.code)) }, highlight: function (e, n, t) { var r = { code: e, grammar: n, language: t }; if (a.hooks.run("before-tokenize", r), !r.grammar) throw new Error('The language "' + r.language + '" has no grammar.'); return r.tokens = a.tokenize(r.code, r.grammar), a.hooks.run("after-tokenize", r), i.stringify(a.util.encode(r.tokens), r.language) }, tokenize: function (e, n) { var t = n.rest; if (t) { for (var r in t) n[r] = t[r]; delete n.rest } var a = new s; return u(a, a.head, e), o(e, a, n, a.head, 0), function (e) { for (var n = [], t = e.head.next; t !== e.tail;)n.push(t.value), t = t.next; return n }(a) }, hooks: { all: {}, add: function (e, n) { var t = a.hooks.all; t[e] = t[e] || [], t[e].push(n) }, run: function (e, n) { var t = a.hooks.all[e]; if (t && t.length) for (var r, i = 0; r = t[i++];)r(n) } }, Token: i }; function i(e, n, t, r) { this.type = e, this.content = n, this.alias = t, this.length = 0 | (r || "").length } function l(e, n, t, r) { e.lastIndex = n; var a = e.exec(t); if (a && r && a[1]) { var i = a[1].length; a.index += i, a[0] = a[0].slice(i) } return a } function o(e, n, t, r, s, g) { for (var f in t) if (t.hasOwnProperty(f) && t[f]) { var h = t[f]; h = Array.isArray(h) ? h : [h]; for (var d = 0; d < h.length; ++d) { if (g && g.cause == f + "," + d) return; var v = h[d], p = v.inside, m = !!v.lookbehind, y = !!v.greedy, k = v.alias; if (y && !v.pattern.global) { var x = v.pattern.toString().match(/[imsuy]*$/)[0]; v.pattern = RegExp(v.pattern.source, x + "g") } for (var b = v.pattern || v, w = r.next, A = s; w !== n.tail && !(g && A >= g.reach); A += w.value.length, w = w.next) { var E = w.value; if (n.length > e.length) return; if (!(E instanceof i)) { var P, L = 1; if (y) { if (!(P = l(b, A, e, m)) || P.index >= e.length) break; var S = P.index, O = P.index + P[0].length, j = A; for (j += w.value.length; S >= j;)j += (w = w.next).value.length; if (A = j -= w.value.length, w.value instanceof i) continue; for (var C = w; C !== n.tail && (j < O || "string" == typeof C.value); C = C.next)L++, j += C.value.length; L--, E = e.slice(A, j), P.index -= A } else if (!(P = l(b, 0, E, m))) continue; S = P.index; var N = P[0], _ = E.slice(0, S), M = E.slice(S + N.length), W = A + E.length; g && W > g.reach && (g.reach = W); var z = w.prev; if (_ && (z = u(n, z, _), A += _.length), c(n, z, L), w = u(n, z, new i(f, p ? a.tokenize(N, p) : N, k, N)), M && u(n, w, M), L > 1) { var I = { cause: f + "," + d, reach: W }; o(e, n, t, w.prev, A, I), g && I.reach > g.reach && (g.reach = I.reach) } } } } } } function s() { var e = { value: null, prev: null, next: null }, n = { value: null, prev: e, next: null }; e.next = n, this.head = e, this.tail = n, this.length = 0 } function u(e, n, t) { var r = n.next, a = { value: t, prev: n, next: r }; return n.next = a, r.prev = a, e.length++, a } function c(e, n, t) { for (var r = n.next, a = 0; a < t && r !== e.tail; a++)r = r.next; n.next = r, r.prev = n, e.length -= a } if (e.Prism = a, i.stringify = function e(n, t) { if ("string" == typeof n) return n; if (Array.isArray(n)) { var r = ""; return n.forEach((function (n) { r += e(n, t) })), r } var i = { type: n.type, content: e(n.content, t), tag: "span", classes: ["token", n.type], attributes: {}, language: t }, l = n.alias; l && (Array.isArray(l) ? Array.prototype.push.apply(i.classes, l) : i.classes.push(l)), a.hooks.run("wrap", i); var o = ""; for (var s in i.attributes) o += " " + s + '="' + (i.attributes[s] || "").replace(/"/g, """) + '"'; return "<" + i.tag + ' class="' + i.classes.join(" ") + '"' + o + ">" + i.content + "</" + i.tag + ">" }, !e.document) return e.addEventListener ? (a.disableWorkerMessageHandler || e.addEventListener("message", (function (n) { var t = JSON.parse(n.data), r = t.language, i = t.code, l = t.immediateClose; e.postMessage(a.highlight(i, a.languages[r], r)), l && e.close() }), !1), a) : a; var g = a.util.currentScript(); function f() { a.manual || a.highlightAll() } if (g && (a.filename = g.src, g.hasAttribute("data-manual") && (a.manual = !0)), !a.manual) { var h = document.readyState; "loading" === h || "interactive" === h && g && g.defer ? document.addEventListener("DOMContentLoaded", f) : window.requestAnimationFrame ? window.requestAnimationFrame(f) : window.setTimeout(f, 16) } return a }(_self); "undefined" != typeof module && module.exports && (module.exports = Prism), "undefined" != typeof global && (global.Prism = Prism);
Prism.languages.json = { property: { pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/, lookbehind: !0, greedy: !0 }, string: { pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/, lookbehind: !0, greedy: !0 }, comment: { pattern: /\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/, greedy: !0 }, number: /-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i, punctuation: /[{}[\],]/, operator: /:/, boolean: /\b(?:false|true)\b/, null: { pattern: /\bnull\b/, alias: "keyword" } }, Prism.languages.webmanifest = Prism.languages.json;
!function (n) { var e = /("|')(?:\\(?:\r\n?|\n|.)|(?!\1)[^\\\r\n])*\1/; n.languages.json5 = n.languages.extend("json", { property: [{ pattern: RegExp(e.source + "(?=\\s*:)"), greedy: !0 }, { pattern: /(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/, alias: "unquoted" }], string: { pattern: e, greedy: !0 }, number: /[+-]?\b(?:NaN|Infinity|0x[a-fA-F\d]+)\b|[+-]?(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[eE][+-]?\d+\b)?/ }) }(Prism);
Prism.languages.jsonp = Prism.languages.extend("json", { punctuation: /[{}[\]();,.]/ }), Prism.languages.insertBefore("jsonp", "punctuation", { function: /(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*\()/ });
!function () { if ("undefined" != typeof Prism && "undefined" != typeof document) { var e = "line-numbers", n = /\n(?!$)/g, t = Prism.plugins.lineNumbers = { getLine: function (n, t) { if ("PRE" === n.tagName && n.classList.contains(e)) { var i = n.querySelector(".line-numbers-rows"); if (i) { var r = parseInt(n.getAttribute("data-start"), 10) || 1, s = r + (i.children.length - 1); t < r && (t = r), t > s && (t = s); var l = t - r; return i.children[l] } } }, resize: function (e) { r([e]) }, assumeViewportIndependence: !0 }, i = void 0; window.addEventListener("resize", (function () { t.assumeViewportIndependence && i === window.innerWidth || (i = window.innerWidth, r(Array.prototype.slice.call(document.querySelectorAll("pre.line-numbers")))) })), Prism.hooks.add("complete", (function (t) { if (t.code) { var i = t.element, s = i.parentNode; if (s && /pre/i.test(s.nodeName) && !i.querySelector(".line-numbers-rows") && Prism.util.isActive(i, e)) { i.classList.remove(e), s.classList.add(e); var l, o = t.code.match(n), a = o ? o.length + 1 : 1, u = new Array(a + 1).join("<span></span>"); (l = document.createElement("span")).setAttribute("aria-hidden", "true"), l.className = "line-numbers-rows", l.innerHTML = u, s.hasAttribute("data-start") && (s.style.counterReset = "linenumber " + (parseInt(s.getAttribute("data-start"), 10) - 1)), t.element.appendChild(l), r([s]), Prism.hooks.run("line-numbers", t) } } })), Prism.hooks.add("line-numbers", (function (e) { e.plugins = e.plugins || {}, e.plugins.lineNumbers = !0 })) } function r(e) { if (0 != (e = e.filter((function (e) { var n, t = (n = e, n ? window.getComputedStyle ? getComputedStyle(n) : n.currentStyle || null : null)["white-space"]; return "pre-wrap" === t || "pre-line" === t }))).length) { var t = e.map((function (e) { var t = e.querySelector("code"), i = e.querySelector(".line-numbers-rows"); if (t && i) { var r = e.querySelector(".line-numbers-sizer"), s = t.textContent.split(n); r || ((r = document.createElement("span")).className = "line-numbers-sizer", t.appendChild(r)), r.innerHTML = "0", r.style.display = "block"; var l = r.getBoundingClientRect().height; return r.innerHTML = "", { element: e, lines: s, lineHeights: [], oneLinerHeight: l, sizer: r } } })).filter(Boolean); t.forEach((function (e) { var n = e.sizer, t = e.lines, i = e.lineHeights, r = e.oneLinerHeight; i[t.length - 1] = void 0, t.forEach((function (e, t) { if (e && e.length > 1) { var s = n.appendChild(document.createElement("span")); s.style.display = "block", s.textContent = e } else i[t] = r })) })), t.forEach((function (e) { for (var n = e.sizer, t = e.lineHeights, i = 0, r = 0; r < t.length; r++)void 0 === t[r] && (t[r] = n.children[i++].getBoundingClientRect().height) })), t.forEach((function (e) { var n = e.sizer, t = e.element.querySelector(".line-numbers-rows"); n.style.display = "none", n.innerHTML = "", e.lineHeights.forEach((function (e, n) { t.children[n].style.height = e + "px" })) })) } } }();
!function () { if ("undefined" != typeof Prism) { var e = Object.assign || function (e, t) { for (var n in t) t.hasOwnProperty(n) && (e[n] = t[n]); return e }, t = { "remove-trailing": "boolean", "remove-indent": "boolean", "left-trim": "boolean", "right-trim": "boolean", "break-lines": "number", indent: "number", "remove-initial-line-feed": "boolean", "tabs-to-spaces": "number", "spaces-to-tabs": "number" }; n.prototype = { setDefaults: function (t) { this.defaults = e(this.defaults, t) }, normalize: function (t, n) { for (var r in n = e(this.defaults, n)) { var i = r.replace(/-(\w)/g, (function (e, t) { return t.toUpperCase() })); "normalize" !== r && "setDefaults" !== i && n[r] && this[i] && (t = this[i].call(this, t, n[r])) } return t }, leftTrim: function (e) { return e.replace(/^\s+/, "") }, rightTrim: function (e) { return e.replace(/\s+$/, "") }, tabsToSpaces: function (e, t) { return t = 0 | t || 4, e.replace(/\t/g, new Array(++t).join(" ")) }, spacesToTabs: function (e, t) { return t = 0 | t || 4, e.replace(RegExp(" {" + t + "}", "g"), "\t") }, removeTrailing: function (e) { return e.replace(/\s*?$/gm, "") }, removeInitialLineFeed: function (e) { return e.replace(/^(?:\r?\n|\r)/, "") }, removeIndent: function (e) { var t = e.match(/^[^\S\n\r]*(?=\S)/gm); return t && t[0].length ? (t.sort((function (e, t) { return e.length - t.length })), t[0].length ? e.replace(RegExp("^" + t[0], "gm"), "") : e) : e }, indent: function (e, t) { return e.replace(/^[^\S\n\r]*(?=\S)/gm, new Array(++t).join("\t") + "$&") }, breakLines: function (e, t) { t = !0 === t ? 80 : 0 | t || 80; for (var n = e.split("\n"), i = 0; i < n.length; ++i)if (!(r(n[i]) <= t)) { for (var o = n[i].split(/(\s+)/g), a = 0, l = 0; l < o.length; ++l) { var s = r(o[l]); (a += s) > t && (o[l] = "\n" + o[l], a = s) } n[i] = o.join("") } return n.join("\n") } }, "undefined" != typeof module && module.exports && (module.exports = n), Prism.plugins.NormalizeWhitespace = new n({ "remove-trailing": !0, "remove-indent": !0, "left-trim": !0, "right-trim": !0 }), Prism.hooks.add("before-sanity-check", (function (e) { var n = Prism.plugins.NormalizeWhitespace; if ((!e.settings || !1 !== e.settings["whitespace-normalization"]) && Prism.util.isActive(e.element, "whitespace-normalization", !0)) if (e.element && e.element.parentNode || !e.code) { var r = e.element.parentNode; if (e.code && r && "pre" === r.nodeName.toLowerCase()) { for (var i in null == e.settings && (e.settings = {}), t) if (Object.hasOwnProperty.call(t, i)) { var o = t[i]; if (r.hasAttribute("data-" + i)) try { var a = JSON.parse(r.getAttribute("data-" + i) || "true"); typeof a === o && (e.settings[i] = a) } catch (e) { } } for (var l = r.childNodes, s = "", c = "", u = !1, m = 0; m < l.length; ++m) { var f = l[m]; f == e.element ? u = !0 : "#text" === f.nodeName && (u ? c += f.nodeValue : s += f.nodeValue, r.removeChild(f), --m) } if (e.element.children.length && Prism.plugins.KeepMarkup) { var d = s + e.element.innerHTML + c; e.element.innerHTML = n.normalize(d, e.settings), e.code = e.element.textContent } else e.code = s + e.code + c, e.code = n.normalize(e.code, e.settings) } } else e.code = n.normalize(e.code, e.settings) })) } function n(t) { this.defaults = e({}, t) } function r(e) { for (var t = 0, n = 0; n < e.length; ++n)e.charCodeAt(n) == "\t".charCodeAt(0) && (t += 3); return e.length + t } }();
!function () { if ("undefined" != typeof Prism && "undefined" != typeof document) { var e = [], t = {}, n = function () { }; Prism.plugins.toolbar = {}; var a = Prism.plugins.toolbar.registerButton = function (n, a) { var r; r = "function" == typeof a ? a : function (e) { var t; return "function" == typeof a.onClick ? ((t = document.createElement("button")).type = "button", t.addEventListener("click", (function () { a.onClick.call(this, e) }))) : "string" == typeof a.url ? (t = document.createElement("a")).href = a.url : t = document.createElement("span"), a.className && t.classList.add(a.className), t.textContent = a.text, t }, n in t ? console.warn('There is a button with the key "' + n + '" registered already.') : e.push(t[n] = r) }, r = Prism.plugins.toolbar.hook = function (a) { var r = a.element.parentNode; if (r && /pre/i.test(r.nodeName) && !r.parentNode.classList.contains("code-toolbar")) { var o = document.createElement("div"); o.classList.add("code-toolbar"), r.parentNode.insertBefore(o, r), o.appendChild(r); var i = document.createElement("div"); i.classList.add("toolbar"); var l = e, d = function (e) { for (; e;) { var t = e.getAttribute("data-toolbar-order"); if (null != t) return (t = t.trim()).length ? t.split(/\s*,\s*/g) : []; e = e.parentElement } }(a.element); d && (l = d.map((function (e) { return t[e] || n }))), l.forEach((function (e) { var t = e(a); if (t) { var n = document.createElement("div"); n.classList.add("toolbar-item"), n.appendChild(t), i.appendChild(n) } })), o.appendChild(i) } }; a("label", (function (e) { var t = e.element.parentNode; if (t && /pre/i.test(t.nodeName) && t.hasAttribute("data-label")) { var n, a, r = t.getAttribute("data-label"); try { a = document.querySelector("template#" + r) } catch (e) { } return a ? n = a.content : (t.hasAttribute("data-url") ? (n = document.createElement("a")).href = t.getAttribute("data-url") : n = document.createElement("span"), n.textContent = r), n } })), Prism.hooks.add("complete", r) } }();
!function () { function t(t) { var e = document.createElement("textarea"); e.value = t.getText(), e.style.top = "0", e.style.left = "0", e.style.position = "fixed", document.body.appendChild(e), e.focus(), e.select(); try { var o = document.execCommand("copy"); setTimeout((function () { o ? t.success() : t.error() }), 1) } catch (e) { setTimeout((function () { t.error(e) }), 1) } document.body.removeChild(e) } "undefined" != typeof Prism && "undefined" != typeof document && (Prism.plugins.toolbar ? Prism.plugins.toolbar.registerButton("copy-to-clipboard", (function (e) { var o = e.element, n = function (t) { var e = { copy: "Copy", "copy-error": "Press Ctrl+C to copy", "copy-success": "Copied!", "copy-timeout": 5e3 }; for (var o in e) { for (var n = "data-Prismjs-" + o, c = t; c && !c.hasAttribute(n);)c = c.parentElement; c && (e[o] = c.getAttribute(n)) } return e }(o), c = document.createElement("button"); c.className = "copy-to-clipboard-button", c.setAttribute("type", "button"); var r = document.createElement("span"); return c.appendChild(r), u("copy"), function (e, o) { e.addEventListener("click", (function () { !function (e) { navigator.clipboard ? navigator.clipboard.writeText(e.getText()).then(e.success, (function () { t(e) })) : t(e) }(o) })) }(c, { getText: function () { return o.textContent }, success: function () { u("copy-success"), i() }, error: function () { u("copy-error"), setTimeout((function () { !function (t) { window.getSelection().selectAllChildren(t) }(o) }), 1), i() } }), c; function i() { setTimeout((function () { u("copy") }), n["copy-timeout"]) } function u(t) { r.textContent = n[t], c.setAttribute("data-copy-state", t) } })) : console.warn("Copy to Clipboard plugin loaded before Toolbar plugin.")) }();
When published the line numbers appear wrapped into a single number as shown below:
Line numbers appear wrapped up
When zooming in or out, the line numbers appear good.
Line numbers appear ok when zooming in or out
When the same code block is added outside the expander, the line numbers appear correctly.
What could be the issue?

Error when selecting row in DataTable after generate table for the second time

Try to create multiple selection table with DataTable. But the problem is, if the table is recreated multiple times. It shows error Cannot read properties of undefined (reading '_DTTT_selected') when select row table . But it's working properly on the first table generate
Here's my JS code
Error is shown when selecting row after run getTable function for the second time
function getTable(){
$("#tblDisbursement").DataTable().clear();
$("#tblDisbursement").DataTable().destroy();
var a = generateDatatables();
}
function generateDatatables() {
$.ajax({
type: "POST",
url: "${local_server}/controller/gettableFilter",
data: $("#formDDL").serialize(),
async:true,
beforeSend : function(){
showLoadingProg(true,"load data");
},
success: function(e) {
showLoadingProg(false);
console.log("ini e");
console.log(e);
if(e.status!="Success"){
$.alert("Error/ Failed");
}
console.log("oini t");
var n = [];
var a = 0;
$.each(e.data, function(e, t) {
var c = new Object;
$.each(t.loan, function(e, t) {
c.loan_acc_no = null != t.loan_acc_no ? t.loan_acc_no : "", c.loan_cif = null != t.loan_cif ? t.loan_cif : "", c.fullname = null != t.fullname ? t.fullname : "", c.loan_prd_code = null != t.loan_prd_code ? t.loan_prd_code : "", c.loan_disb_amount_needs = null != t.loan_disb_amount_needs ? t.loan_disb_amount_needs : "", c.ldi_req_date = null != t.ldi_req_date ? t.ldi_req_date : "", c.status = null != t.status ? t.status : ""
}), n[a] = c, a++
})
var e= $("#tblDisbursement").DataTable({
data: n,
order: [
[5, 'desc']
],
lengthMenu: [
[10, 25, 50, 100, 200, 300, -1],
[10, 25, 50, 100, 200, 300, "All"]
],
columns: [{
render: function(e, t, n) {
return '<input type="checkbox" class="cekbox" name="acc[]" value="' + n.loan_acc_no + '">'
},
orderable: !1
}, {
data: "loan_acc_no"
}, {
data: "fullname",
}, {
data: "loan_prd_code",
render: function(e, t, n) {
var a = "";
return String(n.loan_prd_code).includes("A06") ? "KiniGajian" : "";
}
}, {
data: "loan_disb_amount_needs",
// className: "txtRigth",
render: function(e, t, n) {
return toRp(n.loan_disb_amount_needs)
}
}, {
data: "ldi_req_date",
render: function(e, t, n) {
return null != e ? n.ldi_req_date.replace("T", " ") : ""
}
}, {
data: "status"
} /* {
render: function(e, t, n) {
var a = "";
var x = (n.cga_nik != "Public")?n.cga_nik:n.loan_cif;
// console.log(n.cga_filename);
return a = null != n.cga_filename ? "<span class="label label-success">Image</span>' : '<span class="label label-default">No Image</span>'
}
}, */
/*{
render: function(e, t, n) {
var a = '<button class="edit btn btn-xs btn-success" id="' + n.loan_acc_no + '" value="' + n.loan_acc_no + '" ><i class=" fa fa-edit"></i></button>';
return a += '<button class="view btn btn-xs btn-info" id="' + n.loan_acc_no + '" value="' + n.loan_acc_no + '" ><i class=" fa fa-eye"></i></button>'
},
orderable: !1
}*/
]
});
var t = new $.fn.dataTable.TableTools(e, {
sSwfPath: "",
sRowSelector: "td:not(:last-child)",
sRowSelect: "multi",
fnRowSelected: function(e) {
console.log(e);
try {
$(e).find("input[type=checkbox]").get(0).checked = !0;
var t = -1;
$.each($(".cekbox"), function(e, n) {
t++
});
var n = 0;
$.each($(".cekbox:checked"), function(e, t) {
n++
}), t == n && 0 == document.getElementById("cek").checked && (document.getElementById("cek").checked = !0), 0 != n && $("#btn-dis-all").removeClass("disabled")
} catch (a) {}
},
fnRowDeselected: function(e) {
try {
console..log(e);
$(e).find("input[type=checkbox]").get(0).checked = !1;
var t = -1;
$.each($(".cekbox"), function(e, n) {
t++
});
var n = 0;
$.each($(".cekbox:checked"), function(e, t) {
n++
}), 0 == n && $("#btn-dis-all").addClass("disabled"), t == n && 1 == document.getElementById("cek").checked && (document.getElementById("cek").checked = !1)
} catch (a) {}
},
sSelectedClass: "success"
});
$("#tblDisbursement > thead > tr > td input[type=checkbox]").eq(0).on("click", function() {
var e = this.checked,
n = 0;
$.each($(".cekbox:checked"), function(e, t) {
n++
}), $(this).closest("table").find("tbody > tr").each(function() {
var a = this;
e ? (t.fnSelect(a), $("#btn-dis-all").removeClass("disabled")) : (t.fnDeselect(a), n >= 1 && $("#btn-dis-all").addClass("disabled"))
})
}),
$("#tblDisbursement").on("click", "tr td input[type=checkbox]", function() {
var e = $(this).closest("tr").get(0),
n = 0;
$.each($(".cekbox:checked"), function(e, t) {
n++
});
var a = -1;
$.each($(".cekbox"), function(e, t) {
a++
}), this.checked ? (t.fnSelect(e), n > 0 && $("#btn-dis-all").removeClass("disabled"), a == n && 0 == document.getElementById("cek").checked && (document.getElementById("cek").checked = !0)) : (t.fnDeselect(e), n > 0 && 1 == document.getElementById("cek").checked && 1 == n && (document.getElementById("cek").checked = !1, $("#btn-dis-all").addClass("disabled")))
})
}

Not real random function in a Blogger widget, it always shows 'neighbor' posts from the past

My blog is 12 years old, I have more than 5000 posts. I am using a widget that shows random posts from a specific label. I set it to show 2 posts in the sidebar, and I noticed that these posts are always 'neighbors', which means they are always from the same month in the past. For example, it's always 2 posts from May 2014, or June 2018. It's never something like: 1 post from May 2014 and the other from June 2018. Do you have any idea what the problem is?
Here is the part of the code which (I believe) contains the mistake:
rand=Math.floor((Math.random()*_vRiO.total_entry)+1);
if(rand+bcd140526_post_count>_vRiO.total_entry){
rand=_vRiO.total_entry-bcd140526_post_count+1;
}
if(rand<1){
rand=1;
}
var _vXsM=HOST+_s7IgU[159];
if(bcd140526_index_label){
_vXsM+=_s7IgU[160]+encodeURIComponent(bcd140526_index_label);
}
_vXsM+=_s7IgU[161]+bcd140526_post_count+_s7IgU[162]+rand+_s7IgU[163];
_fIoT(_vXsM);
}else{
_fYbP(json);
}
}
var _vXsM=HOST+_s7IgU[164];
if(bcd140526_index_label){
_vXsM+=_s7IgU[165]+encodeURIComponent(bcd140526_index_label);
}
_vXsM+=_s7IgU[166];
if(bcd140526_sort_by==_s7IgU[167]){
_vXsM+=_s7IgU[168];
}else{
_vXsM+=_s7IgU[169]+bcd140526_post_count;
}
_vXsM+=_s7IgU[170];_fIoT(_vXsM);
I can't paste the whole code, the website doesn't let me. But you can get it here: https://sneeit.com/blogger-random-recent-specific-label-posts-widget-all-in-one-post-feed-widget/
My settings:
Post Count - 2
Post Order - Random
Specific Label - Summer
Show Thumbnail - Checked
Thumbnail Size - 200
Show Label - No
Show Comment Numbers - No
Show Date - No
Show Author Name - No
Show Readmore - No
Show Snippet - No
Show Copyright - No
Design Style - List
I have painstakingly deobfuscated this extension to be able to check how you could modify it (which should be much easier for you if you still want to), and I see that getting "non-neighbor" random numbers is not what this system is designed to do. choosePost(json) chooses one post by number to be the starting post, and makeWidget (which, bizarrely, uses string concatenation and document.write to generate the widget) just uses the first post_count posts after the chosen post, so your objective is not (easily) doable.
var show_thumbnail = true;
var show_label = false;
var show_comment_numbers = false;
var show_date = false;
var show_author_name = false;
var show_readmore = false;
var show_snippet = false;
var hide_copyright = true;
var snippet_length = 150;
var post_count = 3;
var thumbnail_size = 140; // v1.5, only effect with list style
var sort_by = 'random'; // latest or random
var index_label = 'summer';
var design_style = 'list'; // list or column
var date_format = 'mm/dd/yyyy';
var lang_readmore = 'Readmore';
var HOST = '';
function sourceJSfile(url) {
document.write('<script type="text/javascript" src="' + url + '"<\/script>');
}
function generateDate(pub_date, format) {
pub_date = pub_date.split('-');
date = new Date(pub_date[0], pub_date[1] - 1, pub_date[2].substring(0, 2));
dd = date.getDate();
mm = date.getMonth() + 1;
yyyy = date.getFullYear();
format = format.replace('dd', dd);
format = format.replace('mm', mm);
format = format.replace('yyyy', yyyy);
return format;
}
function cleanContent(content) {
var tgt = '';
var imgtag = '<img ';
var srctag = 'src="';
var quote = '\"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0);
index2 = content.indexOf(quote, index1 + srctag.length);
tgt = content.substring(index1 + srctag.length, index2);
}
if (tgt == '') {
imgtag = 'data-thumbnail-src="';
srctag = '"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0 + imgtag.length);
if (index0 != -1) {
tgt = content.substring(index0 + imgtag.length, index1);
}
}
}
if (tgt == '') {
imgtag = '<iframe ';
srctag = 'src="';
quote = '"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0);
if (index0 != -1) {
index2 = content.indexOf(quote, index1 + srctag.length);
if (index0 != -1) {
tgt = content.substring(index1 + srctag.length, index2);
tgt = tgt.replace("http://www.youtube.com/watch?v=", '');
tgt = tgt.replace("http://www.youtube.com/embed/", '');
tgt = tgt.replace('?rel=0', '');
tgt = 'http://img.youtube.com/vi/' + tgt + '/mqdefault.jpg';
}
}
}
}
return tgt;
}
function jsonProcessor(json) {
var data = new Object();
var regex = /<\S[^>]*>/g;
data.id = json.feed.id.$t;
key = 'blog-';
index = data.id.indexOf(key);
data.id = data.id.substring(index + key.length);
data.id = data.id.replace('.comments', '');
data.cate = new Array();
if ('category' in json.feed) {
for (let i = 0; i < json.feed.category.length; i++) {
data.cate[i] = json.feed.category[i].term;
}
}
data.title = '';
if ('title' in json.feed) {
data.title = json.feed.title.$t;
}
data.subtitle = '';
if ('subtitle' in json.feed) {
data.subtitle = json.feed.subtitle.$t;
}
data.admin = new Object();
data.admin.name = 'Anonymous';
data.admin.uri = '';
data.admin.avatar = 'http://img1.blogblog.com/img/anon36.png';
if ('name' in json.feed.author[0]) {
data.admin.name = json.feed.author[0].name.$t;
}
if ('uri' in json.feed.author[0]) {
data.admin.uri = json.feed.author[0].uri.$t;
}
if ('gd$image' in json.feed.author[0]) {
if (json.feed.author[0].gd$image.src != 'http://img1.blogblog.com/img/blank.gif') {
data.admin.avatar = json.feed.author[0].gd$image.src;
}
}
data.total_entry = Number(json.feed.openSearch$totalResults.$t);
data.start_index = Number(json.feed.openSearch$startIndex.$t);
data.item_per_page = Number(json.feed.openSearch$itemsPerPage.$t);
data.entry_number = 0;
if ('entry' in json.feed) {
data.entry_number = json.feed.entry.length;
}
data.entry = new Array();
for (let i = 0; i < data.entry_number; i++) {
data.entry[i] = new Object();
temp = new Object();
entry = json.feed.entry[i];
temp.id = entry.id.$t;
key = 'post-';
index = temp.id.indexOf(key);
temp.id = temp.id.substring(index + key.length);
temp.published = '';
if ('published' in entry) {
temp.published = entry.published.$t;
}
temp.cate = new Array();
if ('category' in entry) {
for (j = 0; j < entry.category.length; j++) {
temp.cate[j] = entry.category[j].term;
}
}
temp.title = '';
if ('title' in entry) {
temp.title = entry.title.$t;
}
temp.content = '';
if ('content' in entry) {
temp.content = entry.content.$t;
}
temp.summary = '';
if ('summary' in entry) {
temp.summary = entry.summary.$t;
}
if (temp.summary == '') {
temp.summary = temp.content.replace(regex, '');
}
if (temp.content == '') {
temp.content = temp.summary;
}
temp.link = '';
temp.reply_label = 'comments';
if ('link' in entry) {
for (j = 0; j < entry.link.length; j++) {
if (entry.link[j].rel == 'alternate') {
temp.link = entry.link[j].href;
}
if (entry.link[j].rel == 'replies') {
temp.reply_label = entry.link[j].title;
}
}
}
temp.author = new Object();
temp.author.name = 'Anonymous';
temp.author.uri = '';
temp.author.avatar = 'http://img1.blogblog.com/img/anon36.png';
a0 = entry.author[0];
if ('name' in a0) {
temp.author.name = a0.name.$t;
}
if ('uri' in a0) {
temp.author.uri = a0.uri.$t;
}
if ('gd$image' in a0) {
if (a0.gd$image.src != 'http://img1.blogblog.com/blank.gif') {
temp.author.avatar = a0.gd$image.src;
}
}
temp.thumbnail = '';
if ('media$thumbnail' in entry) {
temp.thumbnail = entry.media$thumbnail.url;
}
temp.reply_number = 0;
if ('thr$total' in entry) {
temp.reply_number = Number(entry.thr$total.$t);
}
temp.reply_label = temp.reply_label.replace(temp.reply_number + ' ', '');
temp.reply_to = '';
temp.reply_json = '';
temp.reply_title = '';
if ('thr$in-reply-to' in entry) {
temp.reply_to = entry['thr$in-reply-to'].href;
temp.reply_json = entry['thr$in-reply-to'].source;
temp.reply_json = temp.reply_json.replace('/default/', '/summary/');
temp.reply_json = temp.reply_json + '?alt=json-in-script';
}
temp.pid = '';
if ('gd$extendedProperty' in entry) {
for (j = 0; j < entry.gd$extendedProperty.length; j++) {
if (entry.gd$extendedProperty[j].name == 'blogger.itemClass') {
temp.pid = entry.gd$extendedProperty[j].value;
}
}
}
temp.pid = temp.pid.replace('pid-', '');
data.entry[i] = temp;
}
return data;
}
if (typeof(jquery_included) == 'undefined') {
jquery_included = false;
}
function jqueryLoader() {
if (typeof(jQuery) == 'undefined') {
if (!jquery_included) {
jquery_included = true;
var scriptEl = document.createElement('script');
scriptEl.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js');
scriptEl.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(scriptEl);
}
setTimeout(jqueryLoader, 50);
} else {
if (!($('link[href*="font-awesome.css"]').length)) {
linkEl = document.createElement('link');
linkEl.setAttribute('href', 'http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css');
linkEl.setAttribute('rel', 'stylesheet');
document.head.appendChild(linkEl);
}
}
}
jqueryLoader();
function makeWidget(json) {
var div = '<div style="clear:both!important;float:none;!important;line-height:0!important"></div>';
var jsonOut = jsonProcessor(json);
var docAppend = '';
if (jsonOut.total_entry) {
docAppend += ('<div class="post_feed ' + design_style + ' ' + ((show_thumbnail) ? 'thumb' : 'no-thumb') + '"><ul>');
for (let i = 0; i < jsonOut.total_entry && i < post_count; i++) {
p = jsonOut.entry[i];
docAppend += ('<li class="item item-' + i + '">');
if (!p.thumbnail) {
p.thumbnail = cleanContent(p.content);
}
if (show_thumbnail && p.thumbnail) {
var tgt = p.thumbnail;
if (tgt.indexOf('/s72-c/') != -1){
if (design_style === 'column')
tgt = tgt.replace('/s72-c/', '/s1600/');
else
tgt = tgt.replace('/s72-c/', '/s' + thumbnail_size + '-c/');
} else if (tgt.indexOf('youtube.com') != -1 && tgt.indexOf('/default.') != -1) {
tgt = tgt.replace('/default.', '/mqdefault.');
}
p.thumbnail = tgt;
docAppend += ('<a class="thumbnail" style="width:' + thumbnail_size + 'px;height:' + thumbnail_size + 'px;" href="' + p.link + '"><img src="' + p.thumbnail + '"/></a>');
}
docAppend += '<div class="item-body">';
if (show_label && (typeof(p.cate[0]) != 'undefined')) {
docAppend += ('<a class="cate" href="' + HOST + '/search/label/' + p.cate[0] + '">' + p.cate[0] + '</a>');
}
docAppend += ('<h3 class="title">' + p.title + '</h3>');
if (show_author_name || show_comment_numbers || show_date) {
docAppend += '<div class="meta">';
if (show_author_name) {
docAppend += ('<span class="meta-item author-name"><i class="fa fa-user"></i> ' + p.author.name + '</span>');
}
if (show_comment_numbers) {
docAppend += ('<span class="meta-item comment-number"><i class="fa fa-comment"></i> ' + p.reply_number + '</span>');
}
if (show_comment_numbers) {
docAppend += ('<span class="meta-item date-time"><i class="fa fa-clock-o"></i> ' + generateDate(p.published, date_format) +'</span>');
}
docAppend += (div + '</div>' + div);
}
if (show_snippet) {
if (p.summary.length > snippet_length) {
p.summary = p.summary.substring(0, snippet_length) + '...';
}
if (show_readmore) {
p.summary += ' ' + lang_readmore + '';
}
docAppend += ('<p class="snippet">' + p.summary + '</p>');
}
docAppend += (div + '</div>' + div);
docAppend += ('</li>');
}
docAppend += ('</ul>');
if (!hide_copyright) {
docAppend += div;
docAppend += '<a target="_blank" class="copyright" href="http://www.sneeit.com/2014/05/blogger-random-recent-specific-label-posts-widget-all-in-one-post-feed-widget" style="font-size: 11px!important;text-align:right;visibility: visible;!important;text-indent:0!important;height:auto!important;width:100%!important;position:static!important;color:#999!important;display:block!important;opacity:1!important;">BloggerWidget</a>';
}
docAppend += ('</div>' + div);
} else {
docAppend += '<p><em>Have no posts</em><p>';
}
document.write(docAppend);
}
function choosePost(json) {
if (sort_by == 'random') {
var processedJSON = jsonProcessor(json);
rand = Math.floor((Math.random() * processedJSON.total_entry) + 1);
if (rand + post_count > processedJSON.total_entry) {
rand = processedJSON.total_entry - post_count + 1;
}
if (rand < 1) {
rand = 1;
}
var request = HOST + '/feeds/posts/default';
if (index_label) {
request += '/-/' + encodeURIComponent(index_label);
}
request += '?alt=json-in-script&max-result=' + post_count + '&start-index=' + rand + '&callback=makeWidget';
sourceJSfile(request);
} else {
makeWidget(json);
}
}
var request = HOST + '/feeds/posts/default';
if (index_label) {
request += '/-/' + encodeURIComponent(index_label);
}
request += '?alt=json-in-script';
if (sort_by == 'random') {
request += '&max-results=0';
} else {
request += '&max-results=' + post_count;
}
request += '&callback=choosePost';
sourceJSfile(request);
The modifications will take some work, but the deobfuscated version should be much easier to use. I'd recommend removing jqueryLoader, and to get you started: the API requests are sourceJSfile('/feeds/post/default/-/summer?alt=json-in-script&max-results=1&callback=choosePost'). You'd probably be better off rewriting the thing from scratch than trying to bodge it on top of this code, I think.
PS: This code loads the entire jquery library so it can load some random stylesheet in jqueryLoad.

How to sort and search dom table elements created using ajax

I tried this to search dom elements and display matching rows,but it doesnt work in some columns like duration and bytes.It works for elements which repeat for example if there are 507 value twice in bytes it works but dont work for 411. I am reading file contents and tabulating it, then need to sort rows when header is clicked and apply a filter.
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
margin: auto;
empty-cells: hide;
}
table th
{
background-color: GREY;
color: #333;
font-weight: bold;
cursor:pointer;
}
table th, table td
{
padding: 5px;
border: 1px solid #ccc;
border-color: #ccc;
}
#sear
{
background-color: black;
height:30px;
width:105%;
align : center;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
tr:hover {
background-color: silver;
}
</style>
<meta name="viewport" content="width=device-width,height=device-height, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div id="sear" align = center>
<input type="text" id="filter" placeholder="Search" title="Type a name" >
</div>
<div id="demo" align = center >
</div>
<script>
window.onload = function() {
var demo = document.getElementById("demo");
if(window.XMLHttpRequest){
var xhttp = new XMLHttpRequest();
}
else{
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 || this.status == 0) {
var responseText= xhttp.responseText;
//alert(responseText);
// console.log(this.responseText);
document.getElementById("filter").onkeyup = filterRows;
var ROW_DELIMITER = "\n", CELL_DELIMITER = " ";
var tableObj = { headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user",
"Hierarchy code", "Type"],
rows: []
};
}
function convert(responseText) {
tableObj.rows = convertToArray(responseText);
buildTable(tableObj.headers, tableObj.rows);
};
function convertToArray(text) {
return text.split(ROW_DELIMITER).map(function(row) {
return row.split(CELL_DELIMITER);
});
}
function filterRows() {
var input = this;
var rows = tableObj.rows.filter(function(row) {
var matches = row.filter(function(cell) {
return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
});
return matches.length > 0;
});
buildTable(tableObj.headers, rows);
}
function sortRows() {
var index = this.dataset.index;
tableObj.rows.sort(function(rowA, rowB) {
var textA = rowA[index].toUpperCase(), textB = rowB[index].toUpperCase();
if (textA < textB) {
return -1;
}
if (textA > textB) {
return 1;
}
return 0;
});
buildTable(tableObj.headers, tableObj.rows);
}
function buildTable(headers, rows) {
var table = document.createElement('table');
var tr = document.createElement('tr');
table.appendChild(tr);
for (var i = 0; i < headers.length; i++) {
th = document.createElement('th');
tr.appendChild(th);
th.innerHTML = headers[i];
th.onclick = sortRows;
th.dataset.index = i;
}
for (var j = 0; j < rows.length-1; j++) {
tr = document.createElement('tr');
table.appendChild(tr);
tr.dataset.index = j;
for (var k = 0; k < rows[j].length ; k++) {
var td = document.createElement('td');
/* if(k==0)
{
var d = new Date( rows[j][k]* 1000),
yyyy = d.getFullYear(),
mm = ('0' + (d.getMonth() + 1)).slice(-2),
dd = ('0' + d.getDate()).slice(-2),
hh = d.getHours(),
h = hh,
min = ('0' + d.getMinutes()).slice(-2),
ampm = 'AM',
time;
if (hh > 12) {
h = hh - 12;
ampm = 'PM';
} else if (hh === 12) {
h = 12;
ampm = 'PM';
} else if (hh == 0) {
h = 12;
}
rows[j][k] = dd + '.' + mm + '.' + yyyy + ', ' + h + ':' + min + ' ' + ampm;
}
*/
tr.appendChild(td);
td.innerHTML = rows[j][k];
td.dataset.index = k;
}
}
demo.innerHTML = '';
demo.appendChild(table);
}
convert(responseText);
};
xhttp.open("GET", "sample.txt", true);
xhttp.send(null);
};
</script>
</body>
</html>
Here is the updated code:
window.onload = function() {
var demo = document.getElementById("demo");
if (window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest();
} else {
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 || this.status == 0) {
var responseText = xhttp.responseText;
console.log(this.responseText);
document.getElementById("filter").onkeyup = filterRows;
var ROW_DELIMITER = "\n",
CELL_DELIMITER = " ";
var tableObj = {
headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user", "Hierarchy code", "Type"],
rows: []
};
}
function convert(responseText) {
if(responseText!='' && typeof responseText != 'undefined'){
tableObj.rows = convertToArray(responseText);
buildTable(tableObj.headers, tableObj.rows);
}
};
function convertToArray(text) {
return text.split(ROW_DELIMITER).map(function(row) {
return row.split(CELL_DELIMITER);
});
}
function filterRows() {
var input = this;
var rows = tableObj.rows.filter(function(row) {
var matches = row.filter(function(cell) {
//console.log(cell.toUpperCase())
// console.log(input.value.toUpperCase())
// console.log(cell.toUpperCase().indexOf(input.value.toUpperCase()))
return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
});
return matches.length > 0;
});
buildTable(tableObj.headers, rows);
}
function sortRows() {
var index = this.dataset.index;
tableObj.rows.sort(function(rowA, rowB) {
var textA = rowA[index].toUpperCase(),
textB = rowB[index].toUpperCase();
if (textA < textB) {
return -1;
}
if (textA > textB) {
return 1;
}
return 0;
});
buildTable(tableObj.headers, tableObj.rows);
}
function buildTable(headers, rows) {
var table = document.createElement('table');
var tr = document.createElement('tr');
table.appendChild(tr);
for (var i = 0; i < headers.length; i++) {
th = document.createElement('th');
tr.appendChild(th);
th.innerHTML = headers[i];
th.onclick = sortRows;
th.dataset.index = i;
}
for (var j = 0; j <= rows.length - 1; j++) {
tr = document.createElement('tr');
table.appendChild(tr);
tr.dataset.index = j;
for (var k = 0; k < rows[j].length; k++) {
var td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = rows[j][k];
td.dataset.index = k;
}
}
demo.innerHTML = '';
demo.appendChild(table);
}
convert(responseText);
};
xhttp.open("GET", "sample.txt", true);
xhttp.send(null);
};

Passing several arguments into react component

I'm working in React and I'm trying to pass several arguments (different sizes) to one method.
I have hard coded 8 sizes with hard coded labels and class names and that works, but it won’t work on the site since the size options will change depending on what other options are already filtered.
I need to make everything more general with more generic functions and loops.
REACT:
import React, { Component, PropTypes } from 'react';
class Sizes extends Component {
constructor(props) {
super(props);
this.state = {
XXS: false,
XS: false,
S: false,
SM: false,
M: false,
L: false,
XL: false,
XXL: false,
};
this.toggleOnOffXXS = this.toggleOnOffXXS.bind(this);
this.toggleOnOffXS = this.toggleOnOffXS.bind(this);
this.toggleOnOffS = this.toggleOnOffS.bind(this);
this.toggleOnOffSM = this.toggleOnOffSM.bind(this);
this.toggleOnOffM = this.toggleOnOffM.bind(this);
this.toggleOnOffL = this.toggleOnOffL.bind(this);
this.toggleOnOffXL = this.toggleOnOffXL.bind(this);
this.toggleOnOffXXL = this.toggleOnOffXXL.bind(this);
}
toggleOnOffXXS() {
this.setState({
XXS: !this.state.XXS
});
}
toggleOnOffXS() {
this.setState({
XS: !this.state.XS
});
}
toggleOnOffS() {
this.setState({
S: !this.state.S
});
}
toggleOnOffSM() {
this.setState({
SM: !this.state.SM
});
}
toggleOnOffM() {
this.setState({
M: !this.state.M
});
}
toggleOnOffL() {
this.setState({
L: !this.state.L
});
}
toggleOnOffXL() {
this.setState({
XL: !this.state.XL
});
}
toggleOnOffXXL() {
this.setState({
XXL: !this.state.XXL
});
}
render() {
let XXS = this.state.XXS ? 'on' : '' ;
XXS += ' filter-filterSize-XXS' ;
let XS = this.state.XS ? 'on' : '' ;
XS += ' filter-filterSize-XS' ;
let S = this.state.S ? 'on' : '' ;
S += ' filter-filterSize-S' ;
let SM = this.state.SM ? 'on' : '' ;
SM += ' filter-filterSize-SM' ;
let M = this.state.M ? 'on' : '' ;
M += ' filter-filterSize-M' ;
let L = this.state.L ? 'on' : '' ;
L += ' filter-filterSize-L' ;
let XL = this.state.XL ? 'on' : '' ;
XL += ' filter-filterSize-XL' ;
let XXL = this.state.XXL ? 'on' : '' ;
XXL += ' filter-filterSize-XXL' ;
return (
<div
className='filter-filterSize-buttons'
>
<a
className={ XXS }
href='#'
onClick={ this.toggleOnOffXXS }
>
{ 'xxs' }
</a>
<a
className={ XS }
href='#'
onClick={ this.toggleOnOffXS }
>
{ 'xs' }
</a>
<a
className={ S }
href='#'
onClick={ this.toggleOnOffS }
>
{ 's' }
</a>
<a
className={ SM }
href='#'
onClick={ this.toggleOnOffSM }
>
{ 's-m' }
</a>
<a
className={ M }
href='#'
onClick={ this.toggleOnOffM }
>
{ 'm' }
</a>
<a
className={ L }
href='#'
onClick={ this.toggleOnOffL }
>
{ 'l' }
</a>
<a
className={ XL }
href='#'
onClick={ this.toggleOnOffXL }
>
{ 'xl' }
</a>
<a
className={ XXL }
onClick={ this.toggleOnOffXXL }
>
{ 'xxl' }
</a>
</div>
);
}
}
export default Sizes;
I was suggested that it should be written in this manner:
toggleState(key) {
let state = {};
state[key] = !this.state[key];
this.setState(XXS);
}
But when I try, everything goes into loop and pretty much craches every time...
Appreciate any help on this.
I'd suggest using just one handler function and generate your links with bindings.
import React, { Component, PropTypes } from 'react';
class Sizes extends Component {
constructor(props) {
super(props);
this.state = {
XXS: false,
XS: false,
S: false,
SM: false,
M: false,
L: false,
XL: false,
XXL: false,
};
this.sizes = ['XXS', 'XS', 'S', 'SM', 'M', 'L', 'XL', 'XXL'];
}
toggleOnOff(size) {
this.setState({
[size]: !this.state.size
});
}
render() {
let XXS = this.state.XXS ? 'on' : '' ;
XXS += ' filter-filterSize-XXS' ;
let XS = this.state.XS ? 'on' : '' ;
XS += ' filter-filterSize-XS' ;
let S = this.state.S ? 'on' : '' ;
S += ' filter-filterSize-S' ;
let SM = this.state.SM ? 'on' : '' ;
SM += ' filter-filterSize-SM' ;
let M = this.state.M ? 'on' : '' ;
M += ' filter-filterSize-M' ;
let L = this.state.L ? 'on' : '' ;
L += ' filter-filterSize-L' ;
let XL = this.state.XL ? 'on' : '' ;
XL += ' filter-filterSize-XL' ;
let XXL = this.state.XXL ? 'on' : '' ;
XXL += ' filter-filterSize-XXL' ;
return (
<div
className='filter-filterSize-buttons'
>
{
this.sizes.map((size) => {
const toggleOnOff = this.toggleOnOff.bind(this, size);
return (
<a href="#" className={[size]} onClick={toggleOnOff}>{size}</a>
)
})
}
</div>
);
}
}
export default Sizes;
I did not test this, but this should fix your project.
I'm sort of trying to divine through the missing code, but I believe that last line should be: this.setState(state);
toggleState(key) {
let state = {};
state[key] = !this.state[key];
this.setState(state);
}
// or, more simply:
toggleState(key) {
this.setState({[key]: !this.state[key]});
}

Resources