Generate random identical object - javascript

function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function init(){
var resArr = [];
for (var i = 0; i < 10; i++) {
var obj = new Object();
obj.q = getRandomInt(3,5);
obj.r = getRandomInt(1,10);
resArr.push(obj);
}
var str = '<table border=1><th>Multiplication</th>';
for (var i = 0; i < resArr.length; i++) {
str+='<tr><td>'+resArr[i].q+' * '+resArr[i].r+' = '+(resArr[i].q *resArr[i].r)+'</td></tr>';
}
str += '</table>';
document.getElementById('multiTable').innerHTML = str;
}
init();
<button type="button" name="button" onclick="init()">Refresh</button>
<div id='multiTable'></div>
Here I am generating random object and pushing to an array. I am really stuck how to check that created object is present or not in array.
I want to generate random number to show in multiplication table.

I created a function simply to check for duplicate objects in the array
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function checkDuplicate(arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].q == obj.q && arr[i].r == obj.r) {
return true;
break;
}
}
}
function init() {
var resArr = [];
for (var i = 0; i < 10; i++) {
var obj = new Object();
obj.q = getRandomInt(3, 5);
obj.r = getRandomInt(1, 10);
if (!checkDuplicate(resArr, obj)) {
resArr.push(obj);
}
else i--;
}
var str = '<table border=1><th>Multiplication</th>';
for (var i = 0; i < resArr.length; i++) {
str += '<tr><td>' + resArr[i].q + ' * ' + resArr[i].r + ' = ' + (resArr[i].q * resArr[i].r) + '</td></tr>';
}
str += '</table>';
document.getElementById('multiTable').innerHTML = str;
}
init();
<button type="button" name="button" onclick="init()">Refresh</button>
<div id='multiTable'></div>

You could use a hash table and insert all random combination into it after checking if already inserted.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function init() {
var resArr = [],
hash = {};
for (var i = 0; i < 10; i++) {
var obj = new Object();
do {
obj.q = getRandomInt(3, 5);
obj.r = getRandomInt(1, 10);
} while (hash[[obj.q, obj.r].join('|')])
hash[[obj.q, obj.r].join('|')] = true;
resArr.push(obj);
}
var str = '<table border=1><th>Multiplication</th>';
for (var i = 0; i < resArr.length; i++) {
str += '<tr><td>' + resArr[i].q + ' * ' + resArr[i].r + ' = ' + (resArr[i].q * resArr[i].r) + '</td></tr>';
}
str += '</table>';
document.getElementById('multiTable').innerHTML = str;
}
init();
<button type="button" name="button" onclick="init()">Refresh</button>
<div id='multiTable'></div>

Try with Array#filter() method .check the matched object length .And change with while loop for always give a 10 result's
updated
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function init() {
var resArr = [];
var i=0;
while (true) {
var obj = new Object();
obj.q = getRandomInt(3, 5);
obj.r = getRandomInt(1, 10);
if(!resArr.filter(a=> a.q == obj.q && a.r == obj.r).length>0){
resArr.push(obj);
i++;
}
if(i == 10){
break;
}
}
var str = '<table border=1><th>Multiplication</th>';
for (var i = 0; i < resArr.length; i++) {
str += '<tr><td>' + resArr[i].q + ' * ' + resArr[i].r + ' = ' + (resArr[i].q * resArr[i].r) + '</td></tr>';
}
str += '</table>';
document.getElementById('multiTable').innerHTML = str;
}
init();
<button type="button" name="button" onclick="init()">Refresh</button>
<div id='multiTable'></div>

Related

JSON Parse issue in React-Native

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;
}

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>

Unexpected end of input JavaScript

Can somebody please tell me what is wrong with the JavaScript in this code? It said "Unexpected end of input", but I do not see any errors. All my statements seem to be ended at some point, and every syntax checker says that no errors were detected.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Slide Editor</title>
<style>
#font-face {
font-family: SegoeUILight;
src: url(Segoe_UI_Light.ttf);
}
* {
font-family: SegoeUILight;
}
</style>
<script src="Slide/RevealJS/lib/js/html5shiv.js"></script>
<script src="Slide/RevealJS/lib/js/head.min.js"></script>
</head>
<body onload="editSlideshow()">
<div id="sl">
<span id="sls"></span>
</div>
<span id="slt"></span>
<div id="editor">
</div>
<script>
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
var name = getURLParameters("show");
var slideCount = 1;
function editSlideshow() {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
slideCount = 1;
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
slideCount = textArray.length;
var slideCnt = textArray.length - 1;
for (var i = 0; i <= slideCnt; i++) {
$("#sls").append('<button onclick = "loadSlide\'' + (i + 1) + '\')" id = "slide_' + (i + 1) + '">Slide ' + (i + 1) + '</button>');
};
$("sl").append('<button onclick = "newSlide()">New Slide</button>');
};
};
function loadSlide(num) {
var array = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (array == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else if (array[num - 1] == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else {
var slideArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = slideArray[num - 1];
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("editTxt").value = text;
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
};
};
function saveSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
var text = document.getElementById("editTxt").value;
var textArray = new Array();
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = document.getElementById("editTxt").value;
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
};
};
function newSlide() {
var nextSlide = slideCount + 1;
$("#sls").append('<button onclick = "loadSlide(\'' + nextSlide + '\')" id = "slide_' + nextSlide.toString() + '">Slide ' + nextSlide.toString() + '</button>');
slideCount = nextSlide;
};
function deleteSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
textArray.splice((num - 1), 1);
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
};
};
</script>
</body>
</html>
You've gotten the punctuation wrong in more than one of your onclick attributes, for instance here:
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
It's missing the opening parenthesis. The reason syntax checks don't immediately catch this is because you're putting code inside a string. Which you should not do.
Since you're using jQuery, how about using .click(function() { ... }) instead of inline attributes? Just be careful to get your captured variables correct.
The problem at line 63
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
Should be:
$("#sl").append('<button onclick = "newSlide()">New Slide</button>');

Need some improvement in xml display

i have implemented this code to display xml in html using javascript
current output
Need something like
Here is my code
function parseXML(R, s) {
var C = R.childNodes;
var str = '';
for (var i = 0; i < C.length; i++) {
var n = C[i];
var f = false;
if (n.nodeType !== 3) {
str += '<br><<span class="nn">' + n.nodeName + '</span>>';
if (n.hasChildNodes()) {
f = true;
str += parseXML(n, s++);
}
str += '</<span class="nn">' + n.nodeName + '</span>>';
} else {
str += '<span class="nv">' + n.nodeValue + '</span>';
}
if (f) {
str += '<br>';
}
}
var str = str.replace(/(<br>)+/g, '<br>');
return str;
}
how i call this
R : xml object
s : initial 0 (i am passing this so that i can display xml as hirarchical view)
Output in second
- is not required
i have post second out as it can be seen while opening xml document in firefox
please ask if any doubt
I solved it myself.
Updated code with the solution
var pre = 0;
function parseXML(R, s) {
var C = R.childNodes;
var str = '';
for (var i = 0; i < C.length; i++) {
var n = C[i];
if (n.nodeType !== 3) {
str += '<br>' + gs(s) + '<b><</b><span class="nn">' + n.nodeName + '</span><b>></b>';
if (n.hasChildNodes()) {
str += parseXML(n, s + 1);
}
if (pre !== 3) {
str += '<br>' + gs(s);
}
str += '<b><</b>/<span class="nn">' + n.nodeName + '</span><b>></b>';
} else {
str += '<span class="nv">' + n.nodeValue + '</span>';
}
pre = n.nodeType;
}
return str;
}

Limit pagination links number javascript

I have this pagination script which works perfectly except for this little issue.
so now I want to limit the navigation numbers.
but I can't pass the (this.currentPage)
window.thisPager= new Pager('comments', 10);
thisPager.init();
thisPager.showPageNav('thisPager', 'pageNavPosition');
thisPager.showPage(1);
function Pager(class_name, itemsPerPage) {
this.class_name = class_name;
this.itemsPerPage = itemsPerPage;
this.currentPage = pageNumber;
this.pages = 0;
this.inited = true;
this.showRecords = function(from, to) {
var rows = $('.' + class_name);
for (var i = 0; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
this.showPage(this.currentPage - 1);
}
this.next = function() {
if (this.currentPage < this.pages) {
this.showPage(this.currentPage + 1);
}
}
this.last = function() {
if (this.currentPage < this.pages) {
this.showPage(this.pages);
}
}
this.first = function() {
if (this.currentPage > 1) {
this.showPage(1);
}
}
this.init = function() {
var rows = $('.' + class_name);
var records = (rows.length);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '<span onClick="'+pagerName+'.first();" class="pg-normal"> « First</span>';
pagerHtml += '<span onClick="' + pagerName + '.prev();" class="pg-normal"> &#171 Prev </span> | ';
for (var page = 1; page <= this.currentpages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onClick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> | ';
pagerHtml += '<span onClick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';
pagerHtml += '<span onClick="'+pagerName+'.last();" class="pg-normal"> Last »</span>';
element.innerHTML = pagerHtml;
}
}
Please follow this link
http://jsfiddle.net/J3Qnx/16/
I'm trying to pass this.currentPage into this
for (var page = 1; page <= this.currentpage + 5; page++)
but it's not working as I expected
please help guys
It looks like this is an issue of using the wrong case. It looks like you're using currentPage throughout your script but your trying to call currentpage in the for loop. Try fixing the case and see if that works.
var class_name = "comments";
var rows = $('.' + class_name);
var itemsPerPage = 10;
var currentPage = 1;
var inited = false;
var pagerName = "thisPager";
var positionId = "pageNavigation";
var records = $('.' + class_name).length;
var pages = Math.ceil(records / itemsPerPage);
showRecords(0, 9);
navigator(currentPage, positionId, pages);
function showRecords(from, to){
for (var i = 0; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}}
function showPage(pageNumber) {
currentPage = pageNumber;
var from = (currentPage - 1) * itemsPerPage;
var to = from + itemsPerPage - 1;
var positionId = "pageNavigation";
var records = $('.' + class_name).length;
var pages = Math.ceil(records / itemsPerPage);
showRecords(from, to, rows);
navigator(currentPage, positionId, pages);
var oldPageAnchor = document.getElementById('pg'+pageNumber);
oldPageAnchor.className = "pg-selected";
}
function navigator(currentPage, positionId, pages){
var element = document.getElementById(positionId);
var pagerHtml = '';
for (var page = currentPage - 4; page <= currentPage + 4; page++)
if (page >= 1)
if (page <= pages)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onClick="showPage(' + page + ');">' + page + '</span> | ';
element.innerHTML = pagerHtml;
}
​

Categories