JSON Parse issue in React-Native - javascript

I'm so lost.
I keep getting this error:
"SAVED SCREEN NETWORK ERROR: , [SyntaxError: JSON Parse error: Unrecognized token '<']
at node_modules/color-string/index.js:90:16 in cs.get.rgb" (Line 90 is right below my console.log in the code down below)
This part:
console.log(match)
if (match[4]) {
if (match[5]) {
rgb[3] = parseFloat(match[4]) * 0.01;
} else {
rgb[3] = parseFloat(match[4]);
}
}
} else if (match = string.match(per)) {
for (i = 0; i < 3; i++) {
rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
}
But when I check the node_modules, I can't understand at all where its even using JSON. I console logged the match and all I'm getting is this:
Array [
"rgb(28, 28, 30)",
"28",
"28",
"30",
undefined,
undefined,
]
I literally don't know what to do anymore, so I'm hoping someone more experienced can help me out on this.
/* MIT license */
var colorNames = require('color-name');
var swizzle = require('simple-swizzle');
var hasOwnProperty = Object.hasOwnProperty;
var reverseNames = {};
// create a list of reverse color names
for (var name in colorNames) {
if (hasOwnProperty.call(colorNames, name)) {
reverseNames[colorNames[name]] = name;
}
}
var cs = module.exports = {
to: {},
get: {}
};
cs.get = function (string) {
var prefix = string.substring(0, 3).toLowerCase();
var val;
var model;
switch (prefix) {
case 'hsl':
val = cs.get.hsl(string);
model = 'hsl';
break;
case 'hwb':
val = cs.get.hwb(string);
model = 'hwb';
break;
default:
val = cs.get.rgb(string);
model = 'rgb';
break;
}
if (!val) {
return null;
}
return {model: model, value: val};
};
cs.get.rgb = function (string) {
if (!string) {
return null;
}
var abbr = /^#([a-f0-9]{3,4})$/i;
var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i;
var rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/;
var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/;
var keyword = /^(\w+)$/;
var rgb = [0, 0, 0, 1];
var match;
var i;
var hexAlpha;
if (match = string.match(hex)) {
hexAlpha = match[2];
match = match[1];
for (i = 0; i < 3; i++) {
// https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19
var i2 = i * 2;
rgb[i] = parseInt(match.slice(i2, i2 + 2), 16);
}
if (hexAlpha) {
rgb[3] = parseInt(hexAlpha, 16) / 255;
}
} else if (match = string.match(abbr)) {
match = match[1];
hexAlpha = match[3];
for (i = 0; i < 3; i++) {
rgb[i] = parseInt(match[i] + match[i], 16);
}
if (hexAlpha) {
rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255;
}
} else if (match = string.match(rgba)) {
for (i = 0; i < 3; i++) {
rgb[i] = parseInt(match[i + 1], 0);
}
console.log(match)
if (match[4]) {
if (match[5]) {
rgb[3] = parseFloat(match[4]) * 0.01;
} else {
rgb[3] = parseFloat(match[4]);
}
}
} else if (match = string.match(per)) {
for (i = 0; i < 3; i++) {
rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
}
if (match[4]) {
if (match[5]) {
rgb[3] = parseFloat(match[4]) * 0.01;
} else {
rgb[3] = parseFloat(match[4]);
}
}
} else if (match = string.match(keyword)) {
if (match[1] === 'transparent') {
return [0, 0, 0, 0];
}
if (!hasOwnProperty.call(colorNames, match[1])) {
return null;
}
rgb = colorNames[match[1]];
rgb[3] = 1;
return rgb;
} else {
return null;
}
for (i = 0; i < 3; i++) {
rgb[i] = clamp(rgb[i], 0, 255);
}
rgb[3] = clamp(rgb[3], 0, 1);
return rgb;
};
cs.get.hsl = function (string) {
if (!string) {
return null;
}
var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/;
var match = string.match(hsl);
if (match) {
var alpha = parseFloat(match[4]);
var h = ((parseFloat(match[1]) % 360) + 360) % 360;
var s = clamp(parseFloat(match[2]), 0, 100);
var l = clamp(parseFloat(match[3]), 0, 100);
var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);
return [h, s, l, a];
}
return null;
};
cs.get.hwb = function (string) {
if (!string) {
return null;
}
var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/;
var match = string.match(hwb);
if (match) {
var alpha = parseFloat(match[4]);
var h = ((parseFloat(match[1]) % 360) + 360) % 360;
var w = clamp(parseFloat(match[2]), 0, 100);
var b = clamp(parseFloat(match[3]), 0, 100);
var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);
return [h, w, b, a];
}
return null;
};
cs.to.hex = function () {
var rgba = swizzle(arguments);
return (
'#' +
hexDouble(rgba[0]) +
hexDouble(rgba[1]) +
hexDouble(rgba[2]) +
(rgba[3] < 1
? (hexDouble(Math.round(rgba[3] * 255)))
: '')
);
};
cs.to.rgb = function () {
var rgba = swizzle(arguments);
return rgba.length < 4 || rgba[3] === 1
? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')'
: 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')';
};
cs.to.rgb.percent = function () {
var rgba = swizzle(arguments);
var r = Math.round(rgba[0] / 255 * 100);
var g = Math.round(rgba[1] / 255 * 100);
var b = Math.round(rgba[2] / 255 * 100);
return rgba.length < 4 || rgba[3] === 1
? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)'
: 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')';
};
cs.to.hsl = function () {
var hsla = swizzle(arguments);
return hsla.length < 4 || hsla[3] === 1
? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)'
: 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')';
};
// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
// (hwb have alpha optional & 1 is default value)
cs.to.hwb = function () {
var hwba = swizzle(arguments);
var a = '';
if (hwba.length >= 4 && hwba[3] !== 1) {
a = ', ' + hwba[3];
}
return 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')';
};
cs.to.keyword = function (rgb) {
return reverseNames[rgb.slice(0, 3)];
};
// helpers
function clamp(num, min, max) {
return Math.min(Math.max(min, num), max);
}
function hexDouble(num) {
var str = Math.round(num).toString(16).toUpperCase();
return (str.length < 2) ? '0' + str : str;
}

Related

Object.defineProperty called on non-object error

I have this error in jQuery about this code .. and i can't fix it .. i don't understand it and the console log ...
Code is a notifications tool in Blogger that runs cookies
Object.defineProperty called on non-object .... at Function.defineProperty ()
$(function() {
var view = settingsnoti["noti-bloghomepageUrl"];
var message = void 0 !== settingsnoti["word"] ? settingsnoti["word"] : "";
var _0x322dc6 = false !== settingsnoti["allow-noti"];
var a_second = void 0 !== settingsnoti.expires ? settingsnoti.expires : 7;
var _0x48e20c = void 0 !== settingsnoti["color"] ? settingsnoti["color"] : "#388d80";
var styleFloat = void 0 !== settingsnoti.float ? settingsnoti.float : "right";
var lessFileName = false !== settingsnoti["ltr"];
language_form = "" !== message ? message : ["تحديد الكل كمقروء", "قبول", "إلغاء", "عرض", "زيارة", "إشعار", "إعلان", "تحديث", "راجع مالجديد!!"];
var load = function(_height) {
return language_form[parseInt(_height - 1)];
};
switch (lessFileName) {
case true:
badge_dir = "ltr-badge";
break;
case false:
default:
badge_dir = "rtl-badge";
}! function($) {
var abbr;
var i = "#notification-badge";
var element = 'input[name="badge[]"]';
var value = "#notibadgeBtn";
$.fn.ihavebadge = function(name, all) {
var map_el = $(this);
var item = $.extend({
"childTypes": settingsnoti,
"delay": 1,
"expires": a_second,
"onAccept": function() {},
"ImageSize": 116,
"substring": 140,
"float": styleFloat,
"ltr": lessFileName,
"bloggcodeNAM": "PicFast",
"bloggcodeURI": "https://blogg-code.blogspot.com",
"macrosid": "AKfycbykx1ZVe0t0qmw4sZ2Pez4iYNFXnv8w6HAANNtXs5VCX38RS_A",
"noImage": "https://3.bp.blogspot.com/-7CnHTs2OKS8/Wo214lKp0KI/AAAAAAAACPk/CD1mAZz7IwI32hkGM3aVbD6Tefw78IkvgCLcBGAs/s72/no-img-300x300-blogg-code.jpg",
"Imgavatar": "https://1.bp.blogspot.com/-mP-2bvOaWuM/XAkrMTFABaI/AAAAAAAADjU/tqSHDVesLcYwQ1rXt1MVvG3TENbJqMvcQCLcBGAs/s72/no-user.png",
"Monthformat": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
}, name);
var types = {
"getstyle": function(p) {
$(p).appendTo($("head"));
},
"b": function(context, data, res, a, f, cb) {
context.prop("checked", cb);
context.attr("data-auto", data).parent().css({
"background-color": res,
"opacity": a,
"pointer-events": f
});
},
"getlocation": function(index) {
if (index) {
setInterval(function() {
window.location.href = index;
}, 2E3);
}
},
"getcopyright": function(delete_behavior_form) {
var artistTrack = '<li class="notirights px ads badg_radius5 styleimpo"><label class="notirights">' + load(7) + ':</label><span class="notirights type">' + item.bloggcodeNAM + '</span><span class="notirights ilink"><a class="notirights badgehover-opa badg_radius30" href="' + item.bloggcodeURI + '" target="_blank">' + load(5) + "</a></span></li>";
if (0 !== $(".notirights").length) {
$(".notirights").each(function() {
if (($(this).css("opacity") < 1 || "hidden" == $(this).css("visibility") || $(this).is(":hidden")) && $(i).is(":visible")) {
types.getlocation(item.bloggcodeURI);
}
});
} else {
$(delete_behavior_form).prepend(artistTrack);
}
}
};
types.getstyle("<style type='text/css'>div#notification-badge .button,div#notification-badge ul li label,#notification-badge input[type=checkbox],div#notification-badge .badgehover-var:hover {color:" + _0x48e20c + ";}div#notification-badge .button.done,#notification-badge input[type=checkbox]:checked::before,div#notification-badge .ilink a {background-color:" + _0x48e20c + ";}div#notification-badge .button.done,div#notification-badge .button.cancel:hover {border: 1px solid " + _0x48e20c + ";}div#notification-badge .styleimpo {display:block!important;opacity:1!important;visibility:visible!important;width:auto!important;height:auto!important;padding:5px!important;background-color:#ffffff!important;border:1px solid" + _0x48e20c + "!important}</style>");
var pix_color = "";
Math.floor(+Math["random"]() + 1);
if ($("body").hasClass("Preview")) {
var retryLinkHref = view.replace(/\/$/, "");
} else {
retryLinkHref = window.location.origin;
}
var requestOrUrl = retryLinkHref.toLowerCase() + "/feeds/posts/default?alt=json-in-script&orderby=updated&start-index=1&max-results=1";
$.ajax({
"url": requestOrUrl,
"dataType": "jsonp",
"type": "GET",
"success": function(xhr, status, custom) {
if ("entry" in xhr.feed) {
var i = 0;
for (; i < xhr.feed.entry.length; i++) {
var data = xhr.feed.entry[i];
var version = 0;
for (; version < data.link.length; version++) {
var result = data.link[version];
if ("replies" == (result = data.link[version]).rel && "text/html" == result.type) {
result.title;
result.href;
}
if ("alternate" == result.rel) {
var replacements = result.href;
if (-1 !== replacements.indexOf(".blogspot.")) {
replacements = replacements.replace("http://", "https://");
}
break;
}
}
var word = item.Monthformat;
var nickname = data.updated.$t;
var _0x4afe5a = nickname.substring(0, 10);
var contentId = _0x4afe5a.substring(0, 4);
var cPointX = _0x4afe5a.substring(5, 7);
var linkCssId = _0x4afe5a.substring(8, 10) + "-" + word[parseInt(cPointX - 1)] + "-" + contentId;
var _0x417c4f = (data.published.$t.substr(0, 10).replace(/\-/g, "_"), data.title.$t);
var height = item.Imgavatar;
if (void 0 !== data.author[0].uri) {
var value = data.author[0].name.$t;
if (data.author[0].gd$image.src.match("blogblog")) {
var whatToScale = height;
} else {
whatToScale = data.author[0].gd$image.src;
}
var heightInCells = whatToScale.replace(/http:\/\//, "https://").replace("/72-c/", "/s220/");
var id = data.author[0].uri.$t;
} else {
value = "Unknown";
heightInCells = height;
id = "javascript:void(0)";
}
if (void 0 !== data.media$thumbnail) {
var entryOrArray = data.media$thumbnail.url;
var id = item.ImageSize;
var timestamp = entryOrArray.replace(/http:\/\//, "https://").replace("/s72-c/", "/s" + id + "/").replace("?imgmax=800", "");
} else {
if (void 0 !== data.content && null != data.content.$t.match(/youtube\.com.*(\?v=|\/embed\/)(.{11})/)) {
var shapePathsCollection = data.content.$t.match(/youtube\.com.*(\?v=|\/embed\/)(.{11})/).pop();
if (11 == shapePathsCollection.length) {
timestamp = "//img.youtube.com/vi/" + shapePathsCollection + "/0.jpg";
}
} else {
if (void 0 !== data.content && null != data.content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/)) {
timestamp = data.content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/)[1];
} else {
timestamp = item.noImage;
}
}
}
if (void 0 !== data.summary) {
var matches = data.summary.$t.replace(/<\S[^>]*>/g, "");
var resizewidth = matches.substring(0, item.substring) + "...";
if (300 < matches.length) {
matches.substring(0, 170);
}
if (100 < matches.length) {
matches.substring(0, 100);
}
} else {
if (void 0 !== data.content) {
var result = data.content.$t.replace(/(<([^>]+)>)/gi, "");
resizewidth = result.substring(0, item.substring) + "...";
if (300 < result.length) {
result.substring(0, 170);
}
if (100 < result.length) {
result.substring(0, 100);
}
} else {
resizewidth = "";
}
}
var _0xb2707 = data.id.$t.split(".post-").pop();
pix_color = pix_color + ('<li class="px badg_radius5"><input type="checkbox" id="badge-id-cookietypeupdated-' + _0xb2707 + '" name="badge[]" value="updated-' + _0xb2707 + '" data-auto="off"/><label for="badge-id-cookietypeupdated-' + _0xb2707 + '">' + load(8) + ':</label>' + load(9) + '<abbr class="timeago idate badg_radius30" title="' + nickname + '">' + linkCssId + '</abbr><span class="icontent"><a class="badgehover-var" href="' + replacements + '" target="_blank"><img class="badg_radius5" src="' + timestamp + '"/>' + _0x417c4f + '</a></span><span class="inameauthor"><a class="badgehover-var" href="' + id + '" target="_blank" rel="nofollow"><img class="badg_radius100" src="' + heightInCells + '"/><i class="authorname">' + value + '</i></a></span></li>');
}
}
var isScaytNode = clone("badgeControl");
var workspace = clone("badgeControlPrefs");
if (isScaytNode && workspace && "reinit" != all) {
var item2 = true;
if (false == isScaytNode) {
item2 = false;
}
filter(item2, item.expires, i);
} else {
$(i).remove();
var summaryHtml = "";
preferences = JSON.parse(workspace);
$.each(item.childTypes, function(canCreateDiscussions, url) {
if ("" !== url.type && "" !== url.value && "" !== url.link && url.type) {
var th_field = "";
if (false !== url.link) {
th_field = '<span class="ilink"><a class="badgehover-opa badg_radius30" href="' + url.link + '" target="_blank">' + load(4) + '</a></span>';
}
summaryHtml = summaryHtml + ('<li class="px badg_radius5"><input type="checkbox" id="badge-id-cookietype' + url.value + '" name="badge[]" value="' + url.value + '" data-auto="off"/><label for="badge-id-cookietype' + url.value + '">' + load(6) + ':</label><span class="type">' + url.type + '</span>' + th_field + '</li>');
}
});
var artistTrack = '<div id="notification-badge" class="' + badge_dir + 'badg_shadowkit badg_radius2" style="display: none;"><div id="badge-types"><p><button class="button btn-top select" id="badge-btn-select" type="button">' + load(1) + '</button></p><ul>' + summaryHtml + pix_color + '</ul></div><p><button class="button btn-bottom done badgehover-opa badg_radius5" id="badge-btn-done" type="button">' + load(2) + '</button><button class="button btn-bottom cancel badg_radius5" id="badge-btn-cancel" type="button">' + load(3) + '</button></p></div>';
$(map_el).append(artistTrack);
setTimeout(function() {
$.each(preferences, function(canCreateDiscussions, domRootID) {
if (1 != $('#badge-id-cookietype' + domRootID).length) {
abbr = $('#badge-id-cookietype' + domRootID).length;
}
});
var d = preferences.length;
var v = $(element).length;
var m = v - d;
if (0 == abbr && (m = v - d + 1), d || (m = v), 10 < m && (m = "+9"), 0 < m) {
var artistTrack = '<span class="' + badge_dir + 'badge alert badg_radius100">' + m + '</span>';
$(value).append(artistTrack).addClass("Animat-notifications");
}
}, item.delay);
$(window).scroll(function() {
fn(i, value);
});
$("body").on("click", value, function() {
if ($(i).is(":hidden")) {
$(i).hide(function() {
$(".badge").remove();
$(value).addClass("active").removeClass("Animat-notifications");
var x;
var orig_top = $(value).offset().top + $(value).height();
if ("left" === item.float) {
x = $(value).offset().left;
$(this).css({
"top": orig_top + "px",
"left": x + "px"
});
} else {
if ("right" === item.float) {
x = $(window).width() - ($(value).offset().left + $(value).outerWidth());
$(this).css({
"top": orig_top + "px",
"right": x + "px"
});
}
}
$.each(preferences, function(canCreateDiscussions, conid) {
if ($.fn.ihavebadge.preference(conid)) {
types.b($("#badge-id-cookietype" + conid), "on", "white", ".4", "none", true);
}
});
}).fadeIn(100);
}
types.getcopyright("#notification-badge ul");
});
$(i).click(function(canCreateDiscussions) {
if ("BUTTON" !== canCreateDiscussions.target.nodeName) {
canCreateDiscussions.stopPropagation();
}
});
$(element).on("change", function() {
if (this.checked) {
types.b($(this), "on", "white", ".4", "auto");
} else {
types.b($(this), "off", "#f8f8f8", "1", "auto");
}
});
$("body").on("click", "#badge-btn-select", function() {
types.b($(element), "on", "white", ".4", "auto", true);
$("#badge-btn-done").trigger("click");
});
$("body").on("click", "#badge-btn-cancel", function() {
fn(i, value);
});
$("body").on("click", "#badge-btn-advanced", function() {
types.b($(element), "off", "#f1f1f1", "1", "auto", false);
});
$("body").on("click", "#badge-btn-done", function() {
filter(true, item.expires, i);
var data = [];
$.each($(element).serializeArray(), function(canCreateDiscussions, nodes) {
data.push(nodes.value);
var item = '#badge-id-cookietype' + nodes.value;
types.b($(item), "on", "white", ".4", "none");
});
trigger("badgeControlPrefs", JSON.stringify(data), 365);
item.onAccept.call(this);
});
}
}
});
};
$.fn.ihavebadge.cookie = function() {
var message = clone("badgeControlPrefs");
return JSON.parse(message);
};
$.fn.ihavebadge.preference = function(_relatedTarget) {
var currentLineStylesCloned = clone("badgeControl");
var data = clone("badgeControlPrefs");
return data = JSON.parse(data), false !== currentLineStylesCloned && (false !== data && -1 !== data.indexOf(_relatedTarget));
};
var filter = function(key, val, enhanced) {
trigger("badgeControl", key, val);
$(enhanced).fadeOut("fast", function() {
fn(this, value);
});
};
var fn = function(id, el) {
$(id).removeAttr("style");
$(el).removeClass("active");
};
var trigger = function(y, x, keys) {
var expected_date2 = new Date;
expected_date2.setTime(expected_date2.getTime() + 24 * keys * 60 * 60 * 1E3);
var _0x491ad2 = "expires=" + expected_date2.toUTCString();
return document.cookie = y + "=" + x + ";" + _0x491ad2 + ";path=/", clone(y);
};
var clone = function(method) {
var data = method + "=";
var PL$13 = decodeURIComponent(document.cookie).split(";");
var PL$17 = 0;
for (; PL$17 < PL$13.length; PL$17++) {
var PL$6 = PL$13[PL$17];
for (;
" " == PL$6.charAt(0);) {
PL$6 = PL$6.substring(1);
}
if (0 === PL$6.indexOf(data)) {
return PL$6.substring(data.length, PL$6.length);
}
}
return false;
};
}(jQuery);
var am_Overlay = {
"onAccept": function() {
console.log("%cnotification saved...", "color:tomato");
}
};
if (true == _0x322dc6) {
$("body").ihavebadge(am_Overlay, "reinit");
} else {
$("#notibadgeBtn").remove();
}
});
how i can fixed it i want to help please .. and thanks you for all :)

state in react is returning back to the original value

I'am trying to implement a rogue like dungeon crawler game in react,I render the map before component mounts once and i later re-render the level using levelRender() function,but my state is returning back to its orginal value which is set by componentWillMount() function.Debugging shows that state is being chaged by levelRender() function but at end it returns to original state,which i think shouldn't be happening.I know my code is bit long but i guess problem lies with way i call componentWillMount() and levelRender() function.
In the game,brown box is the portal which should trigger the levelRender,when it is run over by player which is red box.
here is link to my codepen,use arrow keys to move around :)
const Map = React.createClass({
getInitialState() {
return {
width: 40,
height: 50,
wallRender: 0,
gameLevel: 0,
Probabilities: {
levelA: [3, 5, 2],
levelB: [3.5, 3, 3.5],
levelC: [8, 1, 1]
}
}
},
componentWillMount() {
document.addEventListener("keydown", this.handleKeyDown, false);
var map = [];
var rooms = [];
var render = [];
var level = this.state.gameLevel;
//use rot.js to generate map
var w = this.state.width,
h = this.state.height;
var objects = ["e", "h", "w"];
var probability;
var enemies = [];
var weapon = [];
var health = []
if (level == 0) {
probability = this.state.Probabilities.levelA;
} else if (level == 1) {
probability = this.state.Probabilities.levelB;
} else {
probability = this.state.Probabilities.levelC;
}
// var map = new ROT.Map.Digger();
var data = {};
var rotMap = new ROT.Map.Rogue(w, h);
var display = new ROT.Display({ width: w, height: h, fontSize: 6 });
rotMap.create(function (x, y, type) {
data[x + "," + y] = type;
display.DEBUG(x, y, type);
})
map = rotMap.map;
var rooms = rotMap.rooms;
// console.log(map);
// console.log(rooms)
var playerPosition = [rooms[0][0].x + 1, rooms[0][0].y + 1];
var portalPosition = [rooms[2][2].x + 2, rooms[2][2].y + 2];
// console.log(playerPosition)
map[playerPosition[0]][playerPosition[1]] = "p";
map[portalPosition[0]][portalPosition[1]] = "*";
var pp = playerPosition;
//
// set up enemies and health
rooms.map(function (rooms) {
rooms.map(function (room) {
var rx = room.x; var ry = room.y;
var noe = Math.floor(Math.random() * ((1 + 2) - 2 + 1)) + 2;
for (var i = 0; i < noe; i++) {
// generate enemy postions
var ex = Math.floor(Math.random() * ((room.width + rx) - rx + 1)) + rx;
var ey = Math.floor(Math.random() * ((room.height + ry) - ry + 1)) + ry;
if ((ex >= rx && ex < room.width + rx) && (ey >= ry && ey < room.height + ry)) {
var totalProbability = eval(probability.join("+"));//get total weight (in this case, 10)
var weighedObjects = new Array();//new array to hold "weighted" fruits
var currentObject = 0;
while (currentObject < objects.length) {
for (i = 0; i < probability[currentObject]; i++)
weighedObjects[weighedObjects.length] = objects[currentObject]
currentObject++
}
var randomnumber = Math.floor(Math.random() * totalProbability)
var x = weighedObjects[randomnumber];
if (x == 'e') {
map[ex][ey] = "e";
var stats = {
loc: ex + " " + ey,
health: 50,
damage: 20
}
enemies.push(stats)
} else if (x == 'h') {
map[ex][ey] = "h";
var stats = {
loc: ex + " " + ey,
boost: 80
}
health.push(stats)
} else if (x == 'w') {
map[ex][ey] = "w";
var stats = {
loc: ex + " " + ey,
damageBoost: 40
}
weapon.push(stats)
}
// console.log(ex + " " + ey + " " + (room.width + rx) + " " + (room.height + ry))
}
}
})
})
// place enemy
// console.log(enemies);
// console.log(health);
// console.log(weapon)
// setup field of view
var fov = this.setFov(pp)
this.setState({
gameState: map,
gameRooms: rooms,
playerPosition: playerPosition,
playerHealth: 50,
playerDamage: 5,
portalPosition: portalPosition,
fov: fov,
enemies: enemies,
health: health,
weapon: weapon
});
},
levelRender(){
console.log("level rendered")
var map = [];
var rooms = [];
var render = [];
var level=this.state.gameLevel;
//use rot.js to generate map
var w = this.state.width,
h = this.state.height;
var objects = ["e", "h", "w"];
var probability;
var enemies = [];
var weapon = [];
var health = []
if (level == 0) {
probability = this.state.Probabilities.levelA;
} else if (level == 1) {
probability = this.state.Probabilities.levelB;
} else {
probability = this.state.Probabilities.levelC;
}
// var map = new ROT.Map.Digger();
var data = {};
var rotMap = new ROT.Map.Rogue(w, h);
var display = new ROT.Display({ width: w, height: h, fontSize: 6 });
rotMap.create(function (x, y, type) {
data[x + "," + y] = type;
display.DEBUG(x, y, type);
})
map = rotMap.map;
var rooms = rotMap.rooms;
var playerPosition = [rooms[0][0].x + 1, rooms[0][0].y + 1];
if(level==0 || level ==1){
var portalPosition = [rooms[2][2].x + 2, rooms[2][2].y + 2];
map[portalPosition[0]][portalPosition[1]] = "*";
}else{
var bossPosition = [rooms[2][2].x + 2, rooms[2][2].y + 2];
map[portalPosition[0]][portalPosition[1]] = "boss";
}
map[playerPosition[0]][playerPosition[1]] = "p";
var pp = playerPosition;
//
// set up enemies and health
rooms.map(function (rooms) {
rooms.map(function (room) {
var rx = room.x; var ry = room.y;
var noe = Math.floor(Math.random() * ((1 + 2) - 2 + 1)) + 2;
for (var i = 0; i < noe; i++) {
// generate enemy postions
var ex = Math.floor(Math.random() * ((room.width + rx) - rx + 1)) + rx;
var ey = Math.floor(Math.random() * ((room.height + ry) - ry + 1)) + ry;
if ((ex >= rx && ex < room.width + rx) && (ey >= ry && ey < room.height + ry)) {
var totalProbability = eval(probability.join("+"));//get total weight (in this case, 10)
var weighedObjects = new Array();//new array to hold "weighted" fruits
var currentObject = 0;
while (currentObject < objects.length) {
for (i = 0; i < probability[currentObject]; i++)
weighedObjects[weighedObjects.length] = objects[currentObject]
currentObject++
}
var randomnumber = Math.floor(Math.random() * totalProbability)
var x = weighedObjects[randomnumber];
if (x == 'e') {
map[ex][ey] = "e";
var stats = {
loc: ex + " " + ey,
health: 50,
damage: 20
}
enemies.push(stats)
} else if (x == 'h') {
map[ex][ey] = "h";
var stats = {
loc: ex + " " + ey,
boost: 80
}
health.push(stats)
} else if (x == 'w') {
map[ex][ey] = "w";
var stats = {
loc: ex + " " + ey,
damageBoost: 40
}
weapon.push(stats)
}
// console.log(ex + " " + ey + " " + (room.width + rx) + " " + (room.height + ry))
}
}
})
})
// setup field of view
var fov = this.setFov(pp)
console.log(this.state.gameState)
this.setState({
gameState: map,
gameRooms: rooms,
playerPosition: playerPosition,
bossPosition:bossPosition,
portalPosition: portalPosition,
fov: fov,
enemies: enemies,
health: health,
weapon: weapon
});
console.log(this.state.gameState)
},
setFov(playerPos) {
var pp = playerPos;
var fov = [];
var x = pp[0]; var y = pp[1];
fov.push(x - 2 + "," + (y - 1)); fov.push(x - 2 + "," + y); fov.push(x - 2 + "," + (y + 1));
fov.push(x - 1 + "," + (y - 2)); fov.push(x - 1 + "," + (y - 1)); fov.push(x - 1 + "," + y); fov.push(x - 1 + "," + (y + 1)); fov.push(x - 1 + "," + (y + 2));
fov.push(x + "," + (y - 2)); fov.push(x + "," + (y - 1)); fov.push(x + "," + y); fov.push(x + "," + (y + 1)); fov.push(x + "," + (y + 2));
fov.push(x + 1 + "," + (y - 2)); fov.push(x + 1 + "," + (y - 1)); fov.push(x + 1 + "," + y); fov.push(x + 1 + "," + (y + 1)); fov.push(x + 1 + "," + (y + 2));
fov.push(x + 2 + "," + (y - 1)); fov.push(x + 2 + "," + y); fov.push(x + 2 + "," + (y + 1));
fov.push(x - 3 + "," + y); fov.push(x + 3 + "," + y); fov.push(x + "," + (y - 3)); fov.push(x + "," + (y + 3))
return fov;
},
handleKeyDown(e) {
// left arrow
var playerLoc = this.state.playerPosition;
if (e.keyCode == 37) {
var map = this.state.gameState;
var playerPos = this.state.playerPosition;
var x = playerPos[0], y = playerPos[1];
// console.log(map)
// console.log(playerPos)
if (map[(x)][(y - 1)] == 0 || map[(x)][(y - 1)] == "w" || map[(x)][(y - 1)] == "h" || map[(x)][(y - 1)] == "*") {
if (map[(x)][(y - 1)] == "*") {
var level = this.state.gameLevel + 1;
this.setState({
gameLevel:level
})
this.levelRender();
}
if (map[(x)][(y - 1)] == "h") {
var health = this.state.playerHealth + 30;
this.setState({
playerHealth: health
})
}
if (map[(x)][(y - 1)] == "w") {
var damage = this.state.playerDamage + 20;
this.setState({
playerDamage: damage
})
}
map[x][y] = 0;
map[(x)][(y - 1)] = "p";
playerPos[0] = x
playerPos[1] = y - 1;
}
// change fov
var pp = playerPos;
var fov = this.setFov(pp)
this.setState({
gameState: map,
playerPosition: playerPos,
fov: fov
})
}
// up arrow
if (e.keyCode == 38) {
var map = this.state.gameState;
var playerPos = this.state.playerPosition;
var x = playerPos[0], y = playerPos[1];
// console.log(map)
// console.log(playerPos)
if (map[(x - 1)][(y)] == 0 || map[(x - 1)][(y)] == "w" || map[(x - 1)][(y)] == "h") {
// update player health and damage
if (map[(x - 1)][(y)] == "h") {
var health = this.state.playerHealth + 30;
this.setState({
playerHealth: health
})
}
if (map[(x - 1)][(y)] == "w") {
var damage = this.state.playerDamage + 20;
this.setState({
playerDamage: damage
})
}
map[x][y] = 0;
map[(x - 1)][(y)] = "p";
playerPos[0] = x - 1
playerPos[1] = y;
}
// console.log(map)
// console.log(playerPos)
// change fov
var pp = playerPos;
var fov = this.setFov(pp)
this.setState({
gameState: map,
playerPosition: playerPos,
fov: fov
})
}
// right arrow
if (e.keyCode == 39) {
var map = this.state.gameState;
var playerPos = this.state.playerPosition;
var x = playerPos[0], y = playerPos[1];
// console.log(map)
// console.log(playerPos)
if (map[(x)][(y + 1)] == 0 || map[(x)][(y + 1)] == "w" || map[(x)][(y + 1)] == "h") {
// update player health and damage
if (map[(x)][(y + 1)] == "h") {
var health = this.state.playerHealth + 30;
this.setState({
playerHealth: health
})
}
if (map[(x)][(y + 1)] == "w") {
var damage = this.state.playerDamage + 20;
this.setState({
playerDamage: damage
})
}
map[x][y] = 0;
map[(x)][(y + 1)] = "p";
playerPos[0] = x
playerPos[1] = y + 1;;
}
//console.log(map)
//console.log(playerPos)
// change fov
var pp = playerPos;
var fov = this.setFov(pp)
this.setState({
gameState: map,
playerPosition: playerPos,
fov: fov
})
}
// down arrow
if (e.keyCode == 40) {
var map = this.state.gameState;
var playerPos = this.state.playerPosition;
var x = playerPos[0], y = playerPos[1];
if (map[(x + 1)][(y)] == 0 || map[(x + 1)][(y)] == "w" || map[(x + 1)][(y)] == "h") {
// update player health and damage
if (map[(x + 1)][(y)] == "h") {
var health = this.state.playerHealth + 30;
this.setState({
playerHealth: health
})
}
if (map[(x + 1)][(y)] == "w") {
var damage = this.state.playerDamage + 20;
this.setState({
playerDamage: damage
})
}
map[x][y] = 0;
map[(x + 1)][(y)] = "p";
playerPos[0] = x + 1
playerPos[1] = y;
}
// console.log(map)
// console.log(playerPos)
// change fov
var pp = playerPos;
var fov = this.setFov(pp)
this.setState({
gameState: map,
playerPosition: playerPos,
fov: fov
})
}
},
render() {
// rendering map
var map = this.state.gameState;
var fov = this.state.fov;
if(this.state.gameLevel==1){
console.log(map)
}
var render = [];
for (var i = 0; i < this.state.width; i++) {
var dummy = [];
for (var j = 0; j < this.state.height; j++) {
var arena = { background: "white", color: "white" };
var wallColor = "grey";
var wall = { background: wallColor, color: wallColor, border: "2px solid black" };
var enemy = { background: "blue", color: "blue" };
var player = { background: "red", color: "red" };
var health = { background: "green", color: "green" }
var weapon = { background: "orange", color: "orange" }
var portal = { background: "brown", color: "brown" }
var boss ={background:"yellow",color:"yellow"}
// check if cell is in fov
var val = i + "," + j;
if (map[i][j] == 0) {
// implement field of view
var x = arena;
// if (fov.includes(val)) {
// x.visibility = "visible";
// console.log(val)
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={x}>00;</td>);
} else if (map[i][j] == "p") {
dummy.push(<td style={player}>00;</td>);
} else if (map[i][j] == "e") {
var x = enemy;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td border={5} style={enemy}>00;</td>);
} else if (map[i][j] == "h") {
var x = health;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={health}>00;</td>);
} else if (map[i][j] == "*") {
var x = portal;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={portal}>00;</td>);
}
else if (map[i][j] == "w") {
var x = weapon;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={weapon}>00;</td>);
}else if (map[i][j] == "boss") {
var x = boss;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={boss}>00;</td>);
}
else {
var x = wall;
// if (fov.includes(val)) {
// x.visibility = "visible";
// // console.log(val)
// } else {
// x.visibility = "hidden";
// }
// generate random hue of colors
dummy.push(<td style={wall}>00;</td>);
}
}
render.push(<tr>{dummy}</tr>);
}
return (
<div>
<div id="info">
<span id="health">Health:{this.state.playerHealth} </span>
<span id="damage">Damage:{this.state.playerDamage} </span>
<span id="message">{this.state.playerMessage}</span>
</div>
<div id="gameArea" tabIndex="0" >
<table align="right">
{render}
</table>
</div>
</div>
)
}
})
ReactDOM.render(<Map />, document.getElementById("app"));
You are setting the state in levelRender and overwriting the same with the previous state.
On line 452, this.leverRender is being invoked, which actually sets the new game state (desired). Later, on line 485, state is being overwritten with the variable map which has got the old values, which is responsible for the undesired output. This has to be resolved by setting the state only once, or setting it twice but with updated values of map.

Numbered page navigation script not working for search label and query results

I am working on a blog with custom template which includes this numbered page navigation script below. Script is working in all pages except search results for queries and labels!!! I tried some changes but as I am not a javascript expert and I couldn't make it work... So, any kind of help would be really appreciated!!!
var pageCount = 9;
var displayPageNum = 3;
var upPageWord = "<i class='fa fa-angle-left'></i>";
var downPageWord = "<i class='fa fa-angle-right'></i>";
function showpageCount(x) {
var C = home_page_url;
var E = new Array();
var y = 1;
var H = 1;
var v = 0;
var p = 0;
var G = 0;
var F = "";
var J = "";
var w = "";
for (var z = 0, A; A = x.feed.entry[z]; z++) {
var u = A.published.$t.substring(0, 19) + A.published.$t.substring(23, 29);
timestamp = encodeURIComponent(u);
var i = A.title.$t;
if (i != "") {
if (v == 0 || (v % pageCount == (pageCount - 1))) {
if (C.indexOf(timestamp) != -1) {
y = H
}
if (i != "") {
H++
}
E[E.length] = "/search?updated-max=" + timestamp + "&max-results=" + pageCount
}
}
v++
}
for (var D = 0; D < E.length; D++) {
if (D >= (y - displayPageNum - 1) && D < (y + displayPageNum)) {
if (p == 0 && D == y - 2) {
if (y == 2) {
J = '<span class="showpage">' + upPageWord + "</span>"
} else {
J = '<span class="showpage">' + upPageWord + "</span>"
}
p++
}
if (D == (y - 1)) {
F += '<span class="showpagePoint">' + y + "</span>"
} else {
if (D == 0) {
F += '<span class="showpageNum">1</span>'
} else {
F += '<span class="showpageNum">' + (D + 1) + "</span>"
}
}
if (G == 0 && D == y) {
w = '<span class="showpage"> ' + downPageWord + "</span>";
G++
}
}
}
if (y > 1) {
F = "" + J + " " + F + " "
}
F = '<div class="showpageArea">' + F;
if (y < (H - 1)) {
F += w
}
if (H == 1) {
H++
}
F += "</div>";
var I = document.getElementsByName("pageArea");
var B = document.getElementById("blog-pager");
if (H <= 2) {
F = ""
}
for (var D = 0; D < I.length; D++) {
I[D].innerHTML = F
}
if (I && I.length > 0) {
F = ""
}
if (B) {
B.innerHTML = F
}
}
function showpageCount2(A) {
var F = home_page_url;
var G = new Array();
var J = F.indexOf("/search/label/") != -1;
var M = J ? F.substr(F.indexOf("/search/label/") + 14, F.length) : "";
M = M.indexOf("?") != -1 ? M.substr(0, M.indexOf("?")) : M;
var B = 1;
var L = 1;
var y = 0;
var p = 0;
var K = 0;
var I = "";
var P = "";
var z = "";
var N = '<span class="showpageNum"><a href="/search/label/' + M + "?&max-results=" + pageCount + '">';
var F = home_page_url;
for (var C = 0, D; D = A.feed.entry[C]; C++) {
var x = D.published.$t.substring(0, 19) + D.published.$t.substring(23, 29);
timestamp = encodeURIComponent(x);
var i = D.title.$t;
if (i != "") {
if (y == 0 || (y % pageCount == (pageCount - 1))) {
if (F.indexOf(timestamp) != -1) {
B = L
}
if (i != "") {
L++
}
G[G.length] = "/search/label/" + M + "?updated-max=" + timestamp + "&max-results=" + pageCount
}
}
y++
}
for (var H = 0; H < G.length; H++) {
if (H >= (B - displayPageNum - 1) && H < (B + displayPageNum)) {
if (p == 0 && H == B - 2) {
if (B == 2) {
P = N + upPageWord + "</a></span>"
} else {
P = '<span class="showpage">' + upPageWord + "</span>"
}
p++
}
if (H == (B - 1)) {
I += '<span class="showpagePoint">' + B + "</span>"
} else {
if (H == 0) {
I = N + "1</a></span>"
} else {
I += '<span class="showpageNum">' + (H + 1) + "</span>"
}
}
if (K == 0 && H == B) {
z = '<span class="showpage"> ' + downPageWord + "</span>";
K++
}
}
}
if (B > 1) {
if (!J) {
I = "" + P + " " + I + " "
} else {
I = "" + P + " " + I + " "
}
}
I = '<div class="showpageArea">' + I;
if (B < (L - 1)) {
I += z
}
if (L == 1) {
L++
}
I += "</div>";
var O = document.getElementsByName("pageArea");
var E = document.getElementById("blog-pager");
if (L <= 2) {
I = ""
}
for (var H = 0; H < O.length; H++) {
O[H].innerHTML = I
}
if (O && O.length > 0) {
I = ""
}
if (E) {
E.innerHTML = I
}
}
var home_page_url = location.href;
var thisUrl = home_page_url;
if (thisUrl.indexOf("/search/label/") != -1) {
if (thisUrl.indexOf("?updated-max") != -1) {
var lblname1 = thisUrl.substring(thisUrl.indexOf("/search/label/") + 14, thisUrl.indexOf("?updated-max"))
} else {
var lblname1 = thisUrl.substring(thisUrl.indexOf("/search/label/") + 14, thisUrl.indexOf("?&max"))
}
}
var home_page = "/";
if (thisUrl.indexOf("?q=") == -1) {
if (thisUrl.indexOf("/search/label/") == -1) {
document.write('<script src="' + home_page + 'feeds/posts/summary?alt=json-in-script&callback=showpageCount&max-results=99999" ><\/script>')
} else {
document.write('<script src="' + home_page + "feeds/posts/full/-/" + lblname1 + '?alt=json-in-script&callback=showpageCount2&max-results=99999" ><\/script>')
}
};
We are currently facing the same problem. The pagination links are good for even pages, but not for off pages. The whole script seems quite buggy, but only for 'search keywords'. Will post results if we achieve any progress.

Sum of value in label having same class

I am trying to add all values of class tmpcpa and place result in final_cpa but final_cpa always return 0.
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmpcpa">' + tmp_cpa + "</label>" +' For Final' + ')';
var final_cpa = calculate_final_cpa();
console.log(final_cpa);
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
Surprisingly when i view source code in browser HTML appears as
<label class="tmpcpa">0</label> but when i do inspect element it shows as
<label class="tmpcpa">30.0</label>
Update here is the whole JS. HTML calls process function which ultimately calls calculate_final_cpa()
//"use strict";
function process(arr) {
document.getElementById('txtgrade' + arr[0] + arr[1] + arr[2]).innerHTML = show_grade(document.getElementById('txtpercentage' + arr[0] + arr[1] + arr[2]).value);
if (validateForm(arr)) {
var module_percentage = +document.getElementById('txtpercentage' + arr[0] + arr[1] + arr[2]).value;
var module_credit = +document.getElementById('txtcredit' + arr[0] + arr[1] + arr[2]).innerHTML;
if (!isNaN(module_percentage) || !isNaN(module_credit)) {
module_percentage = 0;
module_credit = 0;
var total_credit_semester = 0;
var sum_module_percentage_x_credit = 0;
for ( i= 2 ; i <= arr[3] + 1 ; i++) {
module_percentage = +document.getElementById('txtpercentage' + arr[0] + arr[1] + i).value;
module_credit = +document.getElementById('txtcredit' + arr[0] + arr[1] + i).innerHTML;
sum_module_percentage_x_credit += module_percentage * module_credit;
total_credit_semester += module_credit;
}
//console.log(module_percentage);
var spa = sum_module_percentage_x_credit / total_credit_semester;
spa = spa.toFixed(1);
document.getElementById('spa' + arr[0] + arr[1]).innerHTML = spa;
calculate_cpa(arr);
}
}
}
function validateForm(arr) {
var isValid = true;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + ' :input').each(function () {
if ($(this).val() === '')
isValid = false;
});
return isValid;
}
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
/*
* Works for 2 semester per level and 3 year course (optimize later)
*/
function calculate_cpa(arr) {
var isValid = true;
for ( i= 1 ; i <= 2 ; i++) {
var spa = document.getElementById('spa' + arr[0] + i).innerHTML;
if (spa == "N/A") {
isValid = false;
}
}
if (isValid) {
var total_credit_level = 0;
var total_spa_x_credit = 0;
for ( i= 1 ; i <= 2 ; i++) {
var arr2= [arr[0], i];
var spa = +document.getElementById('spa' + arr[0] + i).innerHTML;
total_spa_x_credit += spa * getcredits(arr2);
total_credit_level += getcredits(arr2);
}
var cpa = total_spa_x_credit / total_credit_level;
cpa = cpa.toFixed(1);
document.getElementById('cpa' + arr[0]).innerHTML = cpa;
var level = +document.getElementById('level' + arr[0]).innerHTML
var tmp_cpa = ((level / 100) * cpa).toFixed(1);
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label class="tmpcpa">' + tmp_cpa + "</label>" +' For Final' + ')';
var final_cpa = calculate_final_cpa();
console.log(final_cpa);
if (final_cpa != 0) {
var award = show_award(final_cpa);
document.getElementById('award').innerHTML = award;
document.getElementById('finalcpa').innerHTML = final_cpa;
}
}
}
function getcredits(arr) {
var sum = 0;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + ' .sum').each(function () {
sum += parseInt($(this).text())||0;
});
return sum;
}
function show_grade(module_percentage) {
if (isNaN(module_percentage)) {
return 'N/A';
}
if (module_percentage >= 70 && module_percentage <= 100) {
return 'A';
} else if (module_percentage >= 60 && module_percentage < 70) {
return 'B';
} else if (module_percentage >= 50 && module_percentage < 60) {
return 'C';
} else if (module_percentage >= 40 && module_percentage < 50) {
return 'D';
} else {
return 'F';
}
}
function show_award(cpa) {
if (isNaN(cpa)) {
return 'N/A';
}
if (cpa >= 70 && cpa <= 100) {
return 'First Class with Honours';
} else if (cpa >= 60 && cpa < 70) {
return 'Second Class First Division with Honours';
} else if (cpa >= 50 && cpa < 60) {
return 'Second Class Second Division with Honours';
} else if (cpa >= 45 && cpa < 50) {
return 'Third Class with Honours';
} else if (cpa >= 40 && cpa < 45) {
return 'Pass';
} else if (cpa < 40) {
return 'No award';
}
}
you need to be sure you are calling the function after the document is ready.
Also, you are using unassigned value.
</body>
<script>
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
$(document).ready(function(){
var final_cpa = calculate_final_cpa();
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmpcpa">' + final_cpa + "</label>" +' For Final' + ')';
console.log(final_cpa);
});
</script>

I want to delete the object that have inputed to the array

var employees = [];
function add() {
a = {
tr: document.getElementById("trans").value,
namex: document.getElementById("name").value,
pd: document.getElementById("pd").value,
age: document.getElementById("age").value,
income: document.getElementById("income").value
};
employees.push(a.tr + "" + a.namex + "" + a.pd + "" + a.age + "" + a.income + "");
}
function show() {
q = "";
q = q + "";
q = q + "Transaction NumberNameCivil StatusAgeIncome";
q = q + "";
q = q + "";
b = -1;
while (b < (employees.length - 1)) {
b = b + 1;
q = q + "";
q = q + "" + employees[b] + "";
q = q + "";
}
q = q + "";
document.getElementById("qqq").innerHTML = q;
}
function del() {
for (i = 0; i <= a.length; i++) {
e = employees[0];
f = employees[1];
g = employees[2];
h = employees[3];
k = employees[4];
if (e[i] == document.getElementById("trans").value) {
e.splice(i, 1);
f.splice(i, 1);
g.splice(i, 1);
h.splice(i, 1);
k.splice(i, 1);
}
}
}

Categories