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

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

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?

Getting a 500 Internal Server Error Jquery

While everything is running in the software, I get this error when I make a selection from the dropdown list in only one part. Where am I making a mistake? or is it a server error?
I have not received this error in any Laravel before. When trying to get something from a dropdown list, this error comes to the console and there is no reaction on the site.
https://prnt.sc/vaujzf
<script type="text/javascript">
$("ul#product").siblings('a').attr('aria-expanded','true');
$("ul#product").addClass("show");
$("ul#product #adjustment-create-menu").addClass("active");
var lims_product_array = [];
var product_code = [];
var product_name = [];
var product_qty = [];
$('.selectpicker').selectpicker({
style: 'btn-link',
});
$('#lims_productcodeSearch').on('input', function() {
var warehouse_id = $('#warehouse_id').val();
temp_data = $('#lims_productcodeSearch').val();
if (!warehouse_id) {
$('#lims_productcodeSearch').val(temp_data.substring(0, temp_data.length - 1));
alert('Please select Warehouse!');
}
});
$('select[name="warehouse_id"]').on('change', function() {
var id = $(this).val();
$.get('getproduct/' + id, function(data) {
lims_product_array = [];
product_code = data[0];
product_name = data[1];
product_qty = data[2];
$.each(product_code, function(index) {
lims_product_array.push(product_code[index] + ' (' + product_name[index] + ')');
});
});
});
var lims_productcodeSearch = $('#lims_productcodeSearch');
lims_productcodeSearch.autocomplete({
source: function(request, response) {
var matcher = new RegExp(".?" + $.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(lims_product_array, function(item) {
return matcher.test(item);
}));
},
response: function(event, ui) {
if (ui.content.length == 1) {
var data = ui.content[0].value;
$(this).autocomplete( "close" );
productSearch(data);
};
},
select: function(event, ui) {
var data = ui.item.value;
productSearch(data);
}
});
$("#myTable").on('input', '.qty', function() {
rowindex = $(this).closest('tr').index();
checkQuantity($(this).val(), true);
});
$("table.order-list tbody").on("click", ".ibtnDel", function(event) {
rowindex = $(this).closest('tr').index();
$(this).closest("tr").remove();
calculateTotal();
});
$(window).keydown(function(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function() {
if (this === e.target) {
focusNext = true;
}
else if (focusNext) {
$(this).focus();
return false;
}
});
return false;
}
}
});
$('#adjustment-form').on('submit', function(e) {
var rownumber = $('table.order-list tbody tr:last').index();
if (rownumber < 0) {
alert("Please insert product to order table!")
e.preventDefault();
}
});
function productSearch(data) {
$.ajax({
type: 'GET',
url: 'lims_product_search',
data: {
data: data
},
success: function(data) {
var flag = 1;
$(".product-code").each(function(i) {
if ($(this).val() == data[1]) {
rowindex = i;
var qty = parseFloat($('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val()) + 1;
$('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val(qty);
checkQuantity(qty);
flag = 0;
}
});
$("input[name='product_code_name']").val('');
if(flag) {
var newRow = $("<tr>");
var cols = '';
cols += '<td>' + data[0] + '</td>';
cols += '<td>' + data[1] + '</td>';
cols += '<td><input type="number" class="form-control qty" name="qty[]" value="1" required step="any" /></td>';
cols += '<td class="action"><select name="action[]" class="form-control act-val"><option value="-">{{trans("file.Subtraction")}}</option><option value="+">{{trans("file.Addition")}}</option></select></td>';
cols += '<td><button type="button" class="ibtnDel btn btn-md btn-danger">{{trans("file.delete")}}</button></td>';
cols += '<input type="hidden" class="product-code" name="product_code[]" value="' + data[1] + '"/>';
cols += '<input type="hidden" class="product-id" name="product_id[]" value="' + data[2] + '"/>';
newRow.append(cols);
$("table.order-list tbody").append(newRow);
rowindex = newRow.index();
calculateTotal();
}
}
});
}
function checkQuantity(qty) {
var row_product_code = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('td:nth-child(2)').text();
var action = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.act-val').val();
var pos = product_code.indexOf(row_product_code);
if ( (qty > parseFloat(product_qty[pos])) && (action == '-') ) {
alert('Quantity exceeds stock quantity!');
var row_qty = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val();
row_qty = row_qty.substring(0, row_qty.length - 1);
$('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(row_qty);
}
else {
$('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(qty);
}
calculateTotal();
}
function calculateTotal() {
var total_qty = 0;
$(".qty").each(function() {
if ($(this).val() == '') {
total_qty += 0;
} else {
total_qty += parseFloat($(this).val());
}
});
$("#total-qty").text(total_qty);
$('input[name="total_qty"]').val(total_qty);
$('input[name="item"]').val($('table.order-list tbody tr:last').index() + 1);
}
</script>

add ActionLink "Details" "Edit" "Delete" to a ajax list mvc 5

I want to have ActionLink "Details", "Edit" and "Delete" according to ID with an Ajax list, I managed to get my list out with datatable without having my columns in the script as you can see in my code, I would like to add the 3 links at the end of my table.
This is my controller:
[HttpGet]
public string Loadregistrationslist(int draw, int? start, int? length)
{
try
{
int IdFilter = 0;
string textFilter = "";
if (start == null)
{
start = 0;
}
else
{
start -= 1;
}
if (start < 1)
start = 0;
if (length == null)
{
length = 10;
}
var QueryString = HttpContext.Request.QueryString;
var orderBy = QueryString.Get("order[0][column]");
var orderByDir = QueryString.Get("order[0][dir]");
var search = QueryString.Get("search[value]");
var query = db.Registrations.Select(r => new RegistrationsList()
{
ID = r.ID,
FullName = r.LastName + " " + r.FirstName,
Email = r.Email,
BirthDate = r.BirthDate
});
if (search != null) {
int n;
search = search.Trim();
var isNumeric = int.TryParse(search, out n);
if (isNumeric)
{
IdFilter = n;
query = query.Where(x => x.ID == IdFilter);
}
else if (search != "")
{
textFilter = search;
query = query.Where(x => x.FullName.Contains(textFilter) || x.Email.Contains(textFilter));
}
}
string sortOrder = $"{orderBy}_{orderByDir.ToUpper()}";
switch (sortOrder)
{
//FullName
case "1_DESC":
query = query.OrderByDescending(s => s.FullName);
break;
case "1_ASC":
query = query.OrderBy(s => s.FullName);
break;
//Email
case "2_DESC":
query = query.OrderByDescending(s => s.Email);
break;
case "2_ASC":
query = query.OrderBy(s => s.Email);
break;
//ID
case "0_DESC":
query = query.OrderByDescending(s => s.ID);
break;
default: // ID ascending
query = query.OrderBy(s => s.ID);
break;
}
var data = query.Skip((int)start).Take((int)length).ToList<RegistrationsList>();
var lstData = new List<List<string>>();
foreach (var dataRow in data) {
var row = new List<string>() {
dataRow.ID.ToString(), dataRow.FullName, dataRow.Email, dataRow.BirthDate.ToString()
};
lstData.Add(row);
}
var recordsTotal = db.Registrations.Select(x => x.ID).Count();
var recordsFiltered = query.Count();
var response = new DataTablesResponse()
{
draw = draw,
recordsTotal = recordsTotal,
recordsFiltered = recordsFiltered,
data = lstData
};
return JsonConvert.SerializeObject(response, _jsonSerializerSettings);
}
catch (AjaxFunctionalException ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<List<string>>()/*,
errcode = ex.code,
errmessage = ex.Message,
errdata = ex.data*/
}, _jsonSerializerSettings);
}
catch (Exception ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<List<string>>()
/*code = 5000,
message = ex.Message,
data = null*/
}, _jsonSerializerSettings);
}
}
This is my ajax call:
$(document).ready(function ()
{
$("#registrationTable").DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Home/Loadregistrationslist",
"type": "GET",
"datatype": "json"
}
});
});
And this is my html for the table:
<table id="registrationTable" class="table table-striped dt-responsive display datatable dtr-inline" role="grid" aria-describedby="example-1_info">
<thead>
<tr>
<th>
ID
</th>
<th>
#Resource.FullName
</th>
<th>
#Resource.Email
</th>
<th class="sorting_desc_disabled sorting_asc_disabled">
#Resource.BirthDate
</th>
#*<th>
Edit
</th>
<th>
Delete
</th>*#
</tr>
</thead>
</table>
I found the solution, my controller changes a little bit, so here is my new code:
In my controller:
[HttpGet]
public string Loadregistrationslist(int draw, int? start, int? length)
{
try
{
int IdFilter = 0;
string textFilter = "";
if (start == null)
{
start = 0;
}
else
{
start -= 1;
}
if (start < 1)
start = 0;
if (length == null)
{
length = 10;
}
string orderByDir, search;
int orderByIdx;
List<string> cols = ExtractDataSortAndFilter(out orderByIdx, out orderByDir, out search);
var query = db.Registrations.Select(r => new RegistrationsList()
{
ID = r.ID,
FullName = r.LastName + " " + r.FirstName,
Email = r.Email,
BirthDate = r.BirthDate
});
if (search != null)
{
int n;
search = search.Trim();
var isNumeric = int.TryParse(search, out n);
if (isNumeric)
{
IdFilter = n;
query = query.Where(x => x.ID == IdFilter);
}
else if (search != "")
{
textFilter = search;
query = query.Where(x => x.FullName.Contains(textFilter) || x.Email.Contains(textFilter));
}
}
string sortOrder = $"{cols[orderByIdx]}_{orderByDir.ToUpper()}";
switch (sortOrder)
{
//FullName
case "FullName_DESC":
query = query.OrderByDescending(s => s.FullName);
break;
case "FullName_ASC":
query = query.OrderBy(s => s.FullName);
break;
//Email
case "Email_DESC":
query = query.OrderByDescending(s => s.Email);
break;
case "Email_ASC":
query = query.OrderBy(s => s.Email);
break;
//ID
case "ID_DESC":
query = query.OrderByDescending(s => s.ID);
break;
default: // ID ascending
query = query.OrderBy(s => s.ID);
break;
}
var data = new List<RegistrationsList>();
if (length > -1)
{
data = query.Skip((int)start).Take((int)length).ToList<RegistrationsList>();
}
else
{
data = query.Skip((int)start).ToList<RegistrationsList>();
}
/*var lstData = new List<List<string>>();
foreach (var dataRow in data) {
var row = new List<string>() {
dataRow.ID.ToString(), dataRow.FullName, dataRow.Email, dataRow.BirthDate.ToString()
};
lstData.Add(row);
}*/
var recordsTotal = db.Registrations.Select(x => x.ID).Count();
var recordsFiltered = query.Count();
var response = new DataTablesResponse()
{
draw = draw,
recordsTotal = recordsTotal,
recordsFiltered = recordsFiltered,
data = data
};
return JsonConvert.SerializeObject(response, _jsonSerializerSettings);
}
catch (AjaxFunctionalException ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<RegistrationsList>()/*,
errcode = ex.code,
errmessage = ex.Message,
errdata = ex.data*/
}, _jsonSerializerSettings);
}
catch (Exception ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<RegistrationsList>()
/*code = 5000,
message = ex.Message,
data = null*/
}, _jsonSerializerSettings);
}
}
private List<string> ExtractDataSortAndFilter(out int orderByIdx, out string orderByDir, out string search)
{
List<string> cols;
var QueryString = HttpContext.Request.QueryString;
cols = new List<string>();
string colName = null, colNamePath = "";
int colIdx = 0;
do
{
colNamePath = "columns[" + colIdx + "][data]";
colName = QueryString.Get(colNamePath);
cols.Add(colName);
colIdx++;
} while (colName != null);
string orderBy = QueryString.Get("order[0][column]");
orderByDir = QueryString.Get("order[0][dir]");
search = QueryString.Get("search[value]");
orderByIdx = orderBy == null ? 0 : int.Parse(orderBy);
orderByDir = orderByDir == null ? "asc" : orderByDir;
search = search == null ? "" : search;
return cols;
}
and this is my script:
$(document).ready(function () {
$("#registrationTable").DataTable({
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Home/Loadregistrationslist",
"type": "GET",
"datatype": "json"
},
"columns": [
{
data: null,
title: "<input type=\"checkbox\" id=\"btnSelAllStudents\">",
render: function (data, type, row, meta) {
return '<input type="checkbox" id="cbxRegStudent_' + row.ID + '" value="' + row.ID + '">';
},
targets: "no-sort",
orderable: false
},
{ data: "ID", title: "ID" },
{ data: "FullName", title: "#Resource.FullName" },
{ data: "Email", title: "#Resource.Email" },
{ data: "BirthDate", title: "#Resource.BirthDate" },
{
data: null, title: "Actions",
render: function (data, type, row, meta) {
/*return '<input type="button" class="btn-print printrec" id="' + row.ID + '" value="Print"/>';*/
return '#Resource.Profile | #Resource.Edit';
},
targets: "no-sort",
orderable: false
}
],
order: [],
});
$("#btnSelAllStudents").on("change", function (e) {
$("input[id^='cbxRegStudent_']").prop("checked", $(this).prop("checked"));
});
$('#registrationTable').on('processing.dt', function (e, settings, processing) {
$("#btnSelAllStudents").prop("checked", false);
}).dataTable();
});

Alloy 1.8 Update throwing errors with ListView Binding Transforms

After upgrading to latest Alloy1.8 update, I have started getting Script Errors for my Listview Transform functions.
[ERROR] : Script Error {
[ERROR] : column = 17;
[ERROR] : line = 4;
[ERROR] : message = "Can't find variable: PartyName";
[ERROR] : stack = "anonymous\ntemplate#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/underscore.js:1267:28\n__alloyId721#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/appointments/inspectionProposal.js:23:37\ntrigger#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/backbone.js:163:23\nreset#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/backbone.js:746:35\nsuccess#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/backbone.js:759:44\nSync#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/sync/sql.js:180:51\nsync#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy.js:108:28\nfetch#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/backbone.js:763:42\nloadInspectionDetails#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/appointments/inspectionProposal.js:58:43\nController#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/appointments/inspectionProposal.js:377:26\ncreateController#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy.js:232:54\nController#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/appointments/appointmentContainer.js:716:56\ncreateController#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy.js:232:54\nopenNewPage#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/common/common.js:759:41\nfile:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/dashboard/dashboardAppointments.js:615:35";
[ERROR] : }
Here is my transform function which does return transform.PartyName
function addLastInspectedDate(model) {
var transform = model.toJSON();
var appointmentDetailsCollection = Alloy.createCollection(modelConfiguration.appointmentList);
appointmentDetailsCollection.fetch({
query: {
statement: query.getAppointmentListById,
params: [ transform.AppointmentId ]
}
});
appointmentDetailsCollection.each(function(eachRecord) {
var firstName = eachRecord.get("FirstName");
var lastName = eachRecord.get("LastName");
var partyName = "";
partyName += null != firstName ? firstName : "";
partyName += "" == partyName ? null != lastName ? lastName : "" : " " + lastName;
Ti.API.info("partyName:" + partyName);
transform.PartyName = partyName;
transform.StreetName = eachRecord.get("StreetName");
var city = eachRecord.get("City");
var stateCode = eachRecord.get("StateCode");
var postalCode = eachRecord.get("PostalCode");
var addressLine2 = "";
addressLine2 += null != city ? city : "";
addressLine2 += "" == addressLine2 ? (null != stateCode ? stateCode : "") + " " + (null != postalCode ? postalCode : "") : "," + (null != stateCode ? stateCode : "") + " " + (null != postalCode ? postalCode : "");
Ti.API.info("addressLine2:" + addressLine2);
transform.AddressLine2 = addressLine2;
transform.DateLastInspected = transform.DateInspected;
transform.AppointmentId = transform.AppointmentId;
});
return transform;
}
ListView Bindings:
<ItemTemplate name="selectedInspectionProposal" height="Ti.UI.SIZE" backgroundColor="#119050">
<View height="Ti.UI.SIZE" width="Ti.UI.FILL" top="0" bottom="1" backgroundColor="#fff">
<View class="selectedInspectionData vgroup" id="inspectionDataContainerId" top="10">
<Label class="selectedGenInfo" bindId="partyName" id="partyNameId"></Label>
<Label class="selectedGenInfo" bindId="addressLineOne" id="addressLine1Id"></Label>
<Label class="selectedGenInfo" bindId="addressLineTwo" id="addressLine2Id" bottom="15"></Label>
<Label class="selectedGenInfo" bindId="inspectedDate" id="inspectedDateId" bottom="10"></Label>
</View>
</View>
</ItemTemplate>
</Templates>
<ListSection id="section" dataCollection="Inspection" dataTransform="addLastInspectedDate">
<ListItem template="inspectionProposal" partyName:text="{PartyName}" addressLineOne:text="{StreetName}" addressLineTwo:text="{AddressLine2}" inspectedDate:text="{DateLastInspected}" appointmentId:text="{AppointmentId}" selectedBackgroundColor="#119050"></ListItem>
</ListSection>
inspectionProposal.js generated with Alloy 1.8.2
function __alloyId726(e) {
if (e && e.fromAdapter) return;
var opts = __alloyId726.opts || {};
var models = __alloyId725.models;
var len = models.length;
var __alloyId721 = [];
for (var i = 0; len > i; i++) {
var __alloyId722 = models[i];
__alloyId722.__transform = addLastInspectedDate(__alloyId722);
var __alloyId724 = {
template: "inspectionProposal",
partyName: {
text: _.template("{PartyName}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
addressLineOne: {
text: _.template("{StreetName}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
addressLineTwo: {
text: _.template("{AddressLine2}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
inspectedDate: {
text: _.template("{DateLastInspected}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
appointmentId: {
text: _.template("{AppointmentId}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
properties: {
selectedBackgroundColor: "#119050"
}
};
__alloyId721.push(__alloyId724);
}
opts.animation ? $.__views.section.setItems(__alloyId721, opts.animation) : $.__views.section.setItems(__alloyId721);
}
inspectionProposal.js generated with Alloy 1.7.6
function __alloyId742(e) {
if (e && e.fromAdapter) return;
var opts = __alloyId742.opts || {};
var models = __alloyId741.models;
var len = models.length;
var __alloyId737 = [];
for (var i = 0; len > i; i++) {
var __alloyId738 = models[i];
__alloyId738.__transform = addLastInspectedDate(__alloyId738);
var __alloyId740 = {
template: "inspectionProposal",
partyName: {
text: "undefined" != typeof __alloyId738.__transform["PartyName"] ? __alloyId738.__transform["PartyName"] : __alloyId738.get("PartyName")
},
addressLineOne: {
text: "undefined" != typeof __alloyId738.__transform["StreetName"] ? __alloyId738.__transform["StreetName"] : __alloyId738.get("StreetName")
},
addressLineTwo: {
text: "undefined" != typeof __alloyId738.__transform["AddressLine2"] ? __alloyId738.__transform["AddressLine2"] : __alloyId738.get("AddressLine2")
},
inspectedDate: {
text: "undefined" != typeof __alloyId738.__transform["DateLastInspected"] ? __alloyId738.__transform["DateLastInspected"] : __alloyId738.get("DateLastInspected")
},
appointmentId: {
text: "undefined" != typeof __alloyId738.__transform["AppointmentId"] ? __alloyId738.__transform["AppointmentId"] : __alloyId738.get("AppointmentId")
},
properties: {
selectedBackgroundColor: "#119050"
}
};
__alloyId737.push(__alloyId740);
}
opts.animation ? $.__views.section.setItems(__alloyId737, opts.animation) : $.__views.section.setItems(__alloyId737);
}

leaflet Dynamic icon with filter

I'm trying to create an map with the leaflet-simple-csv-master (i'm a beginner). It's really nice and i'd like to show different icons with my types (for exemple 1 icon for schools, one for administrations,...). I succed to show my different icons when i have the map but when i click to the filter, my icons disappear. In fact it doesn't work because it do not recognize my variable when i use the filter and i can read that my img is no more logos/type1.png but logos/undefined.png.
This is my all code.
var basemap = new L.TileLayer(baseUrl, {maxZoom: 17, attribution: baseAttribution, subdomains: subdomains, opacity: opacity});
var center = new L.LatLng(0, 0);
var map = new L.Map('map', {center: center, zoom: 2, maxZoom: maxZoom, layers: [basemap]});
var popupOpts = {
autoPanPadding: new L.Point(5, 50),
autoPan: true
};
var points = L.geoCsv (null, {
firstLineTitles: true,
fieldSeparator: fieldSeparator,
onEachFeature: function (feature, layer) {
var popup = '<div class="popup-content"><table class="table table-striped table-condensed">';
for (var clave in feature.properties) {
var title = points.getPropertyTitle(clave).strip();
var attr = feature.properties[clave];
if (title == labelColumn) {
layer.bindLabel(feature.properties[clave], {className: 'map-label'});
}
if (attr.indexOf('http') === 0) {
attr = '<a target="_blank" href="' + attr + '">'+ attr + '</a>';
}
if (attr) {
popup += '<tr><th>'+title+'</th><td>'+ attr +'</td></tr>';
}
}
popup += "</table></popup-content>";
layer.bindPopup(popup, popupOpts);
},
pointToLayer: function (feature, latlng) {
var logo = feature.properties['type'];
return L.marker(latlng, {
icon:L.icon({
iconUrl: 'logos/'+logo+'.png',
shadowUrl: 'marker-shadow.png',
iconSize: [25,41],
shadowSize: [41, 41],
shadowAnchor: [13, 20]
})
});
},
filter: function(feature, layer) {
total += 1;
if (!filterString) {
hits += 1;
return true;
}
var hit = false;
var lowerFilterString = filterString.toLowerCase().strip();
$.each(feature.properties, function(k, v) {
var value = v.toLowerCase();
if (value.indexOf(lowerFilterString) !== -1) {
hit = true;
hits += 1;
return false;
}
});
return hit;
}
});
var hits = 0;
var total = 0;
var filterString;
var markers = new L.MarkerClusterGroup();
var dataCsv;
var addCsvMarkers = function() {
hits = 0;
total = 0;
filterString = document.getElementById('filter-string').value;
if (filterString) {
$("#clear").fadeIn();
} else {
$("#clear").fadeOut();
}
map.removeLayer(markers);
points.clearLayers();
markers = new L.MarkerClusterGroup(clusterOptions);
points.addData(dataCsv);
markers.addLayer(points);
map.addLayer(markers);
try {
var bounds = markers.getBounds();
if (bounds) {
map.fitBounds(bounds);
}
} catch(err) {
// pass
}
if (total > 0) {
$('#search-results').html("Showing " + hits + " of " + total);
}
return false;
};
var typeAheadSource = [];
function ArrayToSet(a) {
var temp = {};
for (var i = 0; i < a.length; i++)
temp[a[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
function populateTypeAhead(csv, delimiter) {
var lines = csv.split("\n");
for (var i = lines.length - 1; i >= 1; i--) {
var items = lines[i].split(delimiter);
for (var j = items.length - 1; j >= 0; j--) {
var item = items[j].strip();
item = item.replace(/"/g,'');
if (item.indexOf("http") !== 0 && isNaN(parseFloat(item))) {
typeAheadSource.push(item);
var words = item.split(/\W+/);
for (var k = words.length - 1; k >= 0; k--) {
typeAheadSource.push(words[k]);
}
}
}
}
}
if(typeof(String.prototype.strip) === "undefined") {
String.prototype.strip = function() {
return String(this).replace(/^\s+|\s+$/g, '');
};
}
map.addLayer(markers);
$(document).ready( function() {
$.ajax ({
type:'GET',
dataType:'text',
url: dataUrl,
contentType: "text/csv; charset=utf-8",
error: function() {
alert('Error retrieving csv file');
},
success: function(csv) {
dataCsv = csv;
populateTypeAhead(csv, fieldSeparator);
typeAheadSource = ArrayToSet(typeAheadSource);
$('#filter-string').typeahead({source: typeAheadSource});
addCsvMarkers();
}
});
$("#clear").click(function(evt){
evt.preventDefault();
$("#filter-string").val("").focus();
addCsvMarkers();
});
});

Resources