Hi i create a table and fill it randomnly with operand and operators. Now i want to retrieve every 3 element in each row. For example, have a look at the image i have uploaded, I want to retrieve :
+ 4 +
4 + 10
+ 10 +
10 + 2
+ 2 -
2 - -
and push it in another 2 dimensional array. how will i proceed ? Can someone help?

<script type="text/javascript">
    var totalRows = new Array(10);
    var min =1;
    var max =10;


    function getRandom(x,y)
        {return Math.floor(Math.random() * (y - x + 1)) + x;}

    function drawTable() {
        var div_id = document.getElementById('div1');
        var tbl = document.createElement("table");
        tbl.setAttribute("id","table_id") ;
        tbl.setAttribute("border","1") ;
        div_id.appendChild(tbl);
        var tabl_id = document.getElementById("table_id");

        var div_id2 = document.getElementById('div2');
        var node= " ";

        for(var i=0;i<10;i++){
            var row=document.createElement('tr');
            totalRows[i]= new Array(10);
            for(var j=0;j<10;j++){
                var cell=document.createElement('td');
                cell.setAttribute("width","100px") ;
                cell.setAttribute("height","35px") ;
                var k = getRandom(0,1000);
                if ((k%2)==0)
                {
                    totalRows[i][j] = document.createTextNode(getRandom(min,max));

                }
                else{
                    var z=getRandom(0,1000);
                    if ((z%2)==0)
                        {totalRows[i][j] = document.createTextNode("+");}
                    else
                        {totalRows[i][j] = document.createTextNode("-");}
                } 
                cell.appendChild(totalRows[i][j]);
                row.appendChild(cell);


            }
        tabl_id.appendChild(row);


        }
    }





</script>

Recommended Answers

All 12 Replies

Hi Techyworld, again. Hehe. :)

Here, you review and tweak this code as you like: JSFiddle Live Example

/**
 * Converts the tabel value in an array
 * @param elementNode first table row
 * @return array the retrieved value of each rows and cells in 2d array
 */
function retreiveTableValue(firstRow){
    var retrievedValues = [],
        colBuffer = [],
        targetRow = firstRow,
        targetCol;

    while(targetRow){
        //assign the first TD of the row
        targetCol = targetRow.firstElementChild;
        //cleans up the colBuffer for anther use
        colBuffer = [];

        //Loop through each cell for the value
        while(targetCol){
            colBuffer.push(targetCol.innerText.trim());
            targetCol = targetCol.nextElementSibling;
        }

        retrievedValues.push(colBuffer);
        targetRow = targetRow.nextElementSibling;
    }

    return retrievedValues;
}

Let me know if you have any clarifications. Hope that helps.

hehe thanks gon, u'r so nice :)
This line of code, where will it print it? because I'm viewing it in browser.

console.dir(retreiveTableValue(firstRow));

Thank you.
It'll print in the console. You have to open the console.

f12 OR ctrl + shift + i for chrome
ctrl + shift + k for firefox

It does not display anything! :(

Here's an updated one: alerts the value
JSFiddle Live Example

drawTable();

// Get the first tr element
var firstRow = document.getElementsByTagName("tr")[0];
var retArray = retreiveTableValue(firstRow),
    strBuff = "",
    arrayLen = retArray.length;

while (arrayLen--){
    strBuff += ( ( (retArray.shift()).join(",") ) + "\n");
} ;
alert(strBuff);
colBuffer.push(targetCol.innerText.trim());
                targetCol = targetCol.nextElementSibling;

Can you explain to me these 2 lines of code?

Oh.. :D

just use a map on that one. Since you're using a textNode to store the string just get the value.
This snippet will get the value of each node and create a new array out from totalRows; meaning, the arrays has string values, not the textNode object.

var newArray;
newArray = totalRows.map(function(arrayNode){
    return arrayNode.map(function(node){
        return node.nodeValue.trim();
    });
});

colBuffer.push(targetCol.innerText.trim());
targetCol = targetCol.nextElementSibling;

what the first line does is push the trimmed value of the table cell's innerHTML.
The second line on the other hand get's the next element sibling of the current target TD, and assign it as the current target.
if you have this tree:

<td id="currentTarget"></td>
<td id="nextTarget"></td>
<td></td>

The next element sibling of currentTarget is nextTarget.

What if i want to get the values column wise instead of row wise?

You have to loop through each column first then access each rows. I'll leave that you :D
Just show me what you got so far, then I'll help you from there. :)

Actually I'm uusing this snippet. Will i be able to retrieve it column wise with this one?

    var newArray;
    newArray = totalRows.map(function(arrayNode){
    return arrayNode.map(function(node){
    return node.nodeValue.trim();
    });
    });

Yup, you can too. The returned array from that snippet have string values, and not the node values from totalRows.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.