Creating dynamic Javascript arrays
Hello I want to create an array in java script with 2 for loops
var i;
var a;
var total = document.getElementsByName('qm[7]')
var creativity = document.getElementsByName('qm[0]');
var design = document.getElementsByName('qm[1]');
var text = document.getElementsByName('qm[3]');
var motivation = document.getElementsByName('qm[5]');
var depth = document.getElementsByName('qm[6]');
var usefulness = document.getElementsByName('qm[8]');
var research = document.getElementsByName('qm[9]');
ratingArray = new Array(total,creativity,design,text,motivation,depth,usefulness,research);
for(i=0; i < ratingArray.length;i++)
{
for(a=0; a < ratingArray[i].length;a++)
{
if(ratingArray[i][a].checked == true)
{
rateArray = new Array(ratingArray[i][a].value);
}
}
}
and if i return rateArray does it just give the first element any idea?
source to share
You are rewriting the rateArray every time you find a checked element - I suspect you meant to add it instead:
var ratingArray = new Array(total,creativity,design,text,motivation,depth,usefulness,research);
var rateArray = new Array();
for(i=0; i < ratingArray.length;i++)
{
for(a=0; a < ratingArray[i].length;a++)
{
if(ratingArray[i][a].checked == true)
{
rateArray.push(ratingArray[i][a].value);
}
}
}
source to share
Create a new array and push the selected values ββinto the new array.
Detailed description of array functions
var ratingArray = new Array(total,creativity,design,text,motivation,depth,usefulness,research);
var selectedValArray = [];
for(i=0; i < ratingArray.length;i++)
{
for(a=0; a < ratingArray[i].length;a++)
{
if(ratingArray[i][a].checked == true)
{
selectedValArray.push ( ratingArray[i][a].value );
}
}
}
source to share
Statement
document.getElementsByName('qm[7]')
will not work. There are no items that can be named qm[7]
. Did you mean this is your array? In this case, remove the quotes, initialize the array before these operators, and fill it with the names of the elements you want to select.
The function getElementsByName
returns an array of elements. To use this array, you need to select the elements in it. I.e:.
var elems = document.getElementsByName("body");
var myBody = elems[0];
you are doing it right in your for-loops.
Update: extended section and added explanation on getElementsByTagName
source to share
In this line, you create a new array every time:
rateArray = new Array(ratingArray[i][a].value);
So you have to insert elements into the array instead of creating a new one every time you also delete the latest version.
var rateArray =[]
for(i=0; i < ratingArray.length;i++)
{
for(a=0; a < ratingArray[i].length;a++)
{
if(ratingArray[i][a].checked)
{
rateArray.push(ratingArray[i][a].value);
}
}
}
source to share