saideep
saideep

Reputation: 35

how to set the tables rows which are in loop to an array

i had a loop which is used to create a table....my problem is to push the rows which are in the table to an array using javascript.i had tried but my output is coming in this way

[" cap ", " crocin", "123"] 

[" cap ", " crocin", "123", " choclate ", " silk", "123"] 

i want the output in this way

[" cap ", " crocin", "123"] 

[" choclate ", " silk", "123"]

this is my code

function addProducts(){

    array=[];
    var checkBox=document.getElementsByName("check");
    console.log(checkBox.length);
    var content='';
    for(i=0;i<checkBox.length;i++){
        if(checkBox[i].checked)
        {
            console.log(checkBox[i].parentNode.parentNode.getElementsByTagName("td")[0].textContent); 
            content += '<tr class="sales_details"><td>'+checkBox[i].parentNode.parentNode.getElementsByTagName("td")[0].textContent+'</td><td>'+checkBox[i].parentNode.parentNode.getElementsByTagName("td")[1].textContent+'</td><td>'+checkBox[i].parentNode.parentNode.getElementsByTagName("td")[2].textContent+'</td>
</tr>';

        }
    }
    document.getElementById("selectProduct").innerHTML = content;
}

array1=[];

function sales_det(){

    var salDet=document.getElementsByClassName("sales_details");
    //console.log(salDet.length);
    for (var i = 0; i < salDet.length; i++) {
        var sal=salDet[i].getElementsByTagName("td");
        array1.push(sal[0].textContent,sal[1].textContent,sal[2].textContent,sal[3].textContent);

        console.log(array1);
    }

}  

Upvotes: 0

Views: 49

Answers (2)

Barmar
Barmar

Reputation: 781706

You need to empty the array each time through the loop

function sales_det(){
    var salDet=document.getElementsByClassName("sales_details");
    //console.log(salDet.length);
    for (var i = 0; i < salDet.length; i++) {
        var array1 = [];
        var sal=salDet[i].getElementsByTagName("td");
        array1.push(sal[0].textContent, sal[1].textContent, sal[2].textContent, sal[3].textContent);

        console.log(array1);
    }

}  

Upvotes: 1

ProllyGeek
ProllyGeek

Reputation: 15846

I think you will have to use window to create the new arrays , then push new values:

function sales_det(){

        var salDet=document.getElementsByClassName("sales_details");
        //console.log(salDet.length);
        for (var i = 0; i < salDet.length; i++) {
            var sal=salDet[i].getElementsByTagName("td");
            window["array_"+i] = [];
 window["array_"+i].push(sal[0].textContent,sal[1].textContent,sal[2].textContent,sal[3].textContent);

           console.log(window["array_"+i]);
        }

    }  

Upvotes: 1

Related Questions