2

I am trying to retrieve an array of arrays from a html text input table, but when I look at the array of arrays I get back, its filled with empty strings even though there should be lots of default text and I filled in some more of the cells. Here is the javascript that is called followed by the php used to generate the table. When I click the button, I get

",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"

<script type="text/javascript">
    $(document).ready(function(){
    $("#testButton2").click(function(){
        var tableInfo=document.getElementById("myTable");

        console.log(tableInfo);

        var tableArray= [];
        for (var i = 1; i < tableInfo.rows.length; i++) {
            //var row = tableInfo.rows[i];
            var rowArray = [];
            for (var j = 0; j < tableInfo.rows[i].length; j++) {
                rowArray.push(tableInfo.rows[i].cells[j].innerHtml);
            }
            tableArray.push(rowArray);
        }
        alert(tableArray.toString());
    }); 
});
</script>

<?php
$table = "info.csv";
$id = "myTable";
$count = 0;
echo "<table id=".$id.">\n\n"; 
$f = fopen($table, "r"); 
while (($line = fgetcsv($f)) !== false) {
    echo "<tr>";
    foreach ($line as $cell) {
        if ($count != 0) {
            echo "<td><input value=" . htmlspecialchars($cell) . "></input></td>";
                    } else {
                        echo "<td>" . htmlspecialchars($cell) . "</td>";
                    }    
                }
            echo "</tr>\n";
            $count += 1;
        }
        fclose($f); echo "\n</table>";
?>
5
  • Have you tried file_get_content() versus fopen()? Can you echo just $table and see the read results? Commented Aug 11, 2015 at 17:38
  • In JS there's .innerHtml which doesn't exist, use .innerHTML instead. Commented Aug 11, 2015 at 17:39
  • Oh sorry, your question is in regards to the JavaScript and not the PHP code right? Commented Aug 11, 2015 at 17:39
  • Yeah the reading off of the csv is working fine. No worries :) Commented Aug 11, 2015 at 17:41
  • @Teemu I tried both innerHtml and innerHTML but neither of them worked Commented Aug 11, 2015 at 17:42

4 Answers 4

5

To convert a HTML table to 2d Array iterate its rows TableElement.rows. While iterating over each row loop its cells TableRowElement.cells and collect each textContent of innerHTML.

In a JavaScript ES6 functional fashion it would look like:

const tableToArray = tableId => [...document.querySelector(tableId).rows].map(row => 
  [...row.cells].map(cell => cell.textContent)
);


jQuery( $ => {

  $("#testBtn").on({
    click () {
      const tableArray = tableToArray("#myTable");
      console.log(tableArray);
    }
  });

});
<button id="testBtn">test</button>
<table id="myTable">
  <tr><td>a1</td><td>a2</td><td>a3</td></tr>
  <tr><td>b1</td><td>b2</td><td>b3</td></tr>
  <tr><td>c1</td><td>c2</td><td>c3</td></tr>
  <tr><td>d1</td><td>d2</td><td>d3</td></tr>
</table>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>

Using ol'school for loops and Array.push():

jQuery(function($){
  
    $("#testBtn").click(function() {
        var table = document.getElementById("myTable");
        var arrTable = [];
        
        for (var i = 0; i < table.rows.length; i++) {
            var row = table.rows[i];
            var arrRow = [];
            for(var j = 0; j < row.cells.length; j++) {
                arrRow.push(row.cells[j].textContent);
            }
            arrTable.push(arrRow);
        }
        
        console.log(arrTable);
    }); 
  
});
<button id="testBtn">test</button>
<table id="myTable">
  <tr><td>a1</td><td>a2</td><td>a3</td></tr>
  <tr><td>b1</td><td>b2</td><td>b3</td></tr>
  <tr><td>c1</td><td>c2</td><td>c3</td></tr>
  <tr><td>d1</td><td>d2</td><td>d3</td></tr>
</table>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

0

jsFiddle: http://jsfiddle.net/Twisty/vdsz2gpL/

If your HTML is like so:

<a href="#" id="testButton2">Run</a>
<br />
<br />
<table id="myTable">
    <tr>
        <td>Cell 1</td>
    </tr>
    <tr>
        <td>Cell 2</td>
    </tr>
    <tr>
        <td>Cell 3</td>
    </tr>
</table>

You can make use of .each() in JQuery:

$(document).ready(function () {
    $("#testButton2").click(function () {
        var tableArray = [];
        var tableInfo = $("#myTable");
        $("#myTable tr").each(function (i, row) {
            $(this).find("td").each(function(i, cell){
                tableArray.push($(cell).text());
            });
        });
        alert(tableArray.toString());
    });
});

If you're using JQuery, use it all the way through.

4 Comments

Do jQuery objects have rows collection which has cells collection?
No, they are not, tableInfo is a jQuery object, it has not those collections. Though this is not relevant anymore, since you've edited the answer (btw. not my down vote)
My previous answer was too quick. Whomever downvoted me was correct in doing so at that time. Good point in regards to the objects.
0

I see that an answer has been accepted already but as the question is tagged "jQuery", it may be of interest to see how compact a jQuery solution would be :

$("#testButton2").click(function() {
    var tableArray = $("#myTable tr").map(function(tr) {
        return $("td", tr).map(function(td) {
            return $(td).text();
        }).get();
    }).get();
    console.log(tableArray);
}); 

Comments

-1

It looks like you're using jQuery, try changing the following line

rowArray.push(tableInfo.rows[i].cells[j].innerHtml

to

rowArray.push(tableInfo.rows[i].cells[j].html();

2 Comments

tableInfo.rows[i].cells[j] is a HTMLTDElement, it doesn't have html() method.
I changed the line to rowArray.push(tableInfo.rows[i].cells[j].html()); but the output is still the same :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.