Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating dynamic Arrays Javascript

Hello i want to create a array in java script withing 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 it just gives the first element any idea?

like image 680
streetparade Avatar asked Mar 13 '26 12:03

streetparade


2 Answers

You're overwriting rateArray each time you find a checked element - I suspect you meant to append 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);
                }        
        }

}
like image 161
Greg Avatar answered Mar 15 '26 01:03

Greg


Create a new array and push the selected values to the new array.

A detailed description of array functions

Manipulating JavaScript Arrays

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

}
like image 34
rahul Avatar answered Mar 15 '26 02:03

rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!