Script JS with For Loop over tables - javascript

I am a very beginner with Javascript and I want to write a script that modifies the style of (some) tables, at the end of the parsing of an html page.
I have a (hopefully) MWE of such script:
<script type="application/javascript">
<!--
var Ri = document.getElementsByTagName("tr");
var Ca = document.getElementsByTagName("td");
var nRi = Ri.length;
var nCa = Ca.length;
var nCo = nCa/nRi;
for (var i = 0; i < nCo; i++)
{
Ca[i].style.backgroundColor="rgb(221,247,255)";
}
for (var i = nCo; i < nCa; i = i+nCo)
{
Ca[i].style.backgroundColor="rgb(221,247,255)";
}
//-->
</script>
but, as you can easily verify, it would work correctly only if there's a single table in the html page.
The question is the following. Let us say there are m tables with the attribute class="tabx" in the html page. How can I edit the script so that it counts the m tables with the attribute class="tabx" in the page and, say for j=1,...,m, performs the loops
for (var i = 0; i < nCo; i++)
{
Ca[i].style.backgroundColor="rgb(221,247,255)";
}
for (var i = nCo; i < nCa; i = i+nCo)
{
Ca[i].style.backgroundColor="rgb(221,247,255)";
}
on each of such tables?
Thanks, I couldn't find this in particular on this network with keywords search, and not even in documentation in italian that's plentyful as well...and I know it would take 2 seconds using CSS instead...

Here is how you do it.
var t1 = document.getElementsByClassName("tabx");
for(index = 0; index < t1.length; ++index)
{
var Ri = t1[index].getElementsByTagName("tr");
var Ca = t1[index].getElementsByTagName("td");
var nRi = Ri.length;
var nCa = Ca.length;
var nCo = nCa / nRi;
for (var i = 0; i < nCo; i++) {
Ca[i].style.backgroundColor = "rgb(221,247,255)";
}
for (var i = nCo; i < nCa; i = i + nCo) {
Ca[i].style.backgroundColor = "rgb(221,247,255)";
}
}
http://jsfiddle.net/a5F9b/1/
hope that help.

Related

Javascript; nested for-loop not working

var divs = [];
for (var x = 0; x <= nodeArray.length; x++) {
for (var q = 0; q <= nodeArray.childElementCount; q++) {
divs[x][q] = nodeArray[x].childNodes[q].childNodes[0]
};
};
I need a two dimensional array of the child of every child of a div for multiple divs.
Can't get it to work ;c
Anyone knows if this is even possible with javascript?
Thanks.
Edit:
Thanks guys, it works now! :D
I ended up doing it like this:
var divs = [];
nodeArray.forEach(function(array, index) {
divs[index] = nodeArray[index].children;
});
var imgs = [];
for (var x = 0; x < divs.length; x++) {
imgs[x] = [];
for (var y = 0; y < divs[x].length; y++) {
imgs[x][y] = divs[x][y].childNodes[0];
}
}
Using your feedback it works now! Really really really thanks! ;D
Arrays are 0-indexed, This means that the last element of an array is not at array.length but at array.length - 1.
You'll have to create a new array (sub-array) and then start adding elements to it.
Your code should be like this:
var divs = [];
for (var x = 0; x < nodeArray.length; x++) {
// here ^^^
divs[x] = []; // create a new sub-array (or divs.push([]);)
for (var q = 0; q < nodeArray.childElementCount; q++) {
// here ^^^
divs[x][q] = nodeArray[x].childNodes[q].childNodes[0];
};
};
var divs = [];
for (var x = 0; x <= nodeArray.length; x++) {
divs[x] = [];
for (var q = 0; q <= nodeArray[x].length; q++) {
divs[x][q] = nodeArray[x][q][0];
};
};

I'm having trouble adding these elements of my array together. the dash seems to inhibit the addition of each variable

I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});

Outputting new arrays

I am trying to produce an array by drawing data from two separate databases. I am getting close, but right now the data is output as one string: e.g.
[Smith, [ED-100,Some ClassED-200,Some Other Class]]
I would like the data to be in the form
[Smith, [[ED-100,Some Class], [ED-200,Some Other Class]]]
I have been spending hours fiddling with the code, but seem to have come up short. Here is what I have:
var teacherzCourses = [];
var teacherz = Object.getOwnPropertyNames(uniqTeach).sort();
for (var j = 0; j < teacherz.length; j++) {
var tName;
var tCourses = [];
for (k = 0; k < registrarData.length; k++) {
Object.getOwnPropertyNames(uniqTeach).sort();
// get the courses each teacher does
for (var j = 0; j < teacherz.length; j++) {
tName = teacherz[j];
tCourses = [];
tempArray = [];
for (k = 0; k < registrarData.length; k++) {
if (registrarData[k].Teacher.indexOf(teacherz[j]) > -1) {
console.log([teacherz[j], registrarData[k].CourseNum, registrarData[k].CourseName]);
tCourses += [registrarData[k].CourseNum, registrarData[k].CourseName];
};
tempArray += (tCourses);
};
teacherzCourses.push([tName, tCourses]);
};
};
console.table(teacherzCourses);
console.log(teacherzCourses[0][1]);
};
I have the feeling I am making this much more complicated than it needs to be.
Change this line:
tCourses += [registrarData[k].CourseNum, registrarData[k].CourseName];
to this:
tCourses.push([registrarData[k].CourseNum, registrarData[k].CourseName]);
As jfriend00 mentioned, there's no += operator on arrays.

Javascript create multidimensional array

I try to create a 4-dimensional array. I fill it dynamically and use content of it in another function. But the content is empty. Is there error below code?
var datas = []; // day number of a week
for(var i = 0; i < 7; i++) {
var size = 24*60/timeInterval;
datas[i] = [];
for(var j = 0; j < size; j++) {
var size2 = allCoords.length / 2;
datas[i][j] = [];
for(var k = 0; k < size2; k++) {
datas[i][j][k] = [];
}
}
}
I test below example :
function foo1()
{
datas[0][0][0].push(10);
}
function foo2()
{
document.getElementByID('result').innerHTML = datas[0][0][0];
}
I see only ,,,,,,,.
I think the principal problem is that you're getting the element where you want to show your result badly using getElementByID instead of getElementById. Also make sure that your element has innerHTML property to write the result, or alternatively use value.
I write the follow example using <textArea id="result"></textArea> and generating a button which calls foo1();foo2(); onClick an it works for me.
In the sample I use an random value for timeInterval and allCoords.length.
Note also that you want a 4-dimensional array however you're creating a 3-dimensional.
var timeInterval = 60;
var allCoords = { length : 1};
var datas = []; // day number of a week
for(var i = 0; i < 7; i++) {
var size = 24*60/timeInterval;
datas[i] = [];
for(var j = 0; j < size; j++) {
var size2 = allCoords.length / 2;
datas[i][j] = [];
for(var k = 0; k < size2; k++) {
datas[i][j][k] = [];
}
}
}
function foo1()
{
datas[0][0][0].push(10);
}
function foo2()
{
document.getElementById('result').value = datas[0][0][0];
}
<textArea id="result"></textArea>
<input type="button" value="foo" onclick="foo1();foo2();"/>
Hope this helps,

Can I create a loop for 4 different drop lists?

In spite of this code actually working, I am trying to slim it down to a loop...So far all my attempts have failed. What you will see are four drop lists with different Id's...However, they do have the same class name (optionLinks).
Here is the code:
function init(){
var allE = document.getElementById("executive");
allE.onchange = loadLink;
var allL = document.getElementById("legislative");
allL.onchange = loadLink;
var allJ = document.getElementById("judicial");
allJ.onchange = loadLink;
var allS = document.getElementById("state");
allS.onchange = loadLink;
}
Thanks everyone :)
With a moderately up-to-date browser:
[].forEach.call(document.querySelectorAll('.optionLinks'), function(a){
a.addEventListener('change', loadLink);
});
JS Fiddle demo.
References:
Array.prototype.forEach().
document.querySelectorAll().
Function.prototype.call().
var ids = ['executive','legislative','judicial','state'];
for (var i = 0; i < ids.length; i++)
document.getElementById(ids[i]).onChange = loadLink;
Or...
var elements = document.getElementsByClassName('optionLinks');
for (var i = 0; i < elements.length; i++)
elements[i].onChange = loadLink;
elements = document.getElementsByClassName('optionLinks');
for (var i = 0; i < elements.length; i++) {
elements[i].onchange = loadLink;
}

Categories