Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML table data into arrays via jQuery

I want to extract data from an html table like

<table>
    <tr>
        <th> Header1 </th>
        <th> Header2 </th>
        <th> Header3 </th>
    </tr>
    <tr>
        <td> Value 1,1 </td>
        <td> Value 2,1 </td>
        <td> Value 3,1 </td>
    </tr>

    ... rows ...

</table>

and get arrays:

  • an array for the headers
  • a 2d array for the column values (or an array for each column)

    How can I do this using jQuery?

    I don't care to serialize it, or put it into a JSON object because I want to use it to render a chart.


    related General design question:

    at the moment I have something like

    1. ajax query returns html table
    2. use jQuery to get values from html table
    3. render chart
    

    does it make more sense to throw a JSON object back from the ajax query and then render a table and a chart from there?

  • like image 934
    sova Avatar asked Dec 03 '10 21:12

    sova


    1 Answers

    demo updated http://jsfiddle.net/ish1301/cnsnk/

    var header = Array();
    
    $("table tr th").each(function(i, v){
            header[i] = $(this).text();
    })
    
    alert(header);
    
    var data = Array();
    
    $("table tr").each(function(i, v){
        data[i] = Array();
        $(this).children('td').each(function(ii, vv){
            data[i][ii] = $(this).text();
        }); 
    })
    
    alert(data);
    
    like image 98
    Ish Avatar answered Oct 24 '22 11:10

    Ish