1

I have a html table

<table>
<tr>
<th>Type</th>
<th>Text</th>
<th>Time</th>
<th>Notification Time</th>
</tr>
<tr>
<td>Lab1</td>
<td>Some Text</td>
<td>Day of Week</td>
<td>Monday, Wednessday</td>
</tr>
<tr>
<td>Lab2</td>
<td>Some Text</td>
<td>Day of Week</td>
<td>Tuesday, Wednessday</td>
</tr>
</table>

Now I want to use those values of <td> and form an array in php or jquery. Any idea how to do it in the most simplest way?

Arnab
  • 4,216
  • 2
  • 28
  • 50

3 Answers3

2

In jquery:

var tdCollection = $("table").find("td");
var array = [];
$.each(tdCollection, function(key, el){    
     array.push($(el).text());     
});
console.log(array);

fiddle: http://jsfiddle.net/qqdwct7h/

But it would be better to set an id attribute for the table, beacuse using $(table) isn`t best way to select a certain table.

Alexandr Lazarev
  • 12,554
  • 4
  • 38
  • 47
2

Check this jQuery traversing and Ajax sample :)

<script type="text/javascript">
    var tableRows = $("table tr"),
        currentRow,
        tableData = [];

    for (var i = tableRows.length; i--;) {
        currentRow = $(tableRows[i]);

        tableData.push({
            field1: $(":nth-child(1)", currentRow),
            field2: $(":nth-child(2)", currentRow),
            field3: $(":nth-child(3)", currentRow),
            field4: $(":nth-child(4)", currentRow)
        });
    }

    //Sample Test to verify if data is fetched
    console.log(tableData);

    $.ajax({
        url: "sample-ajax-handler.php",
        type: "POST",
        data: tableData,
        success: function (e) {
            //do what you want here :)
        }
    });
</script>
Allan Chua
  • 9,305
  • 9
  • 41
  • 61
0

I wrote a fiddle that allows to generate an array based on the column:

http://jsfiddle.net/5vfm6k6q/2/

Works like this:

var parser = new ArrayParser(),
    result = parser.getArray('#table', 'Type');  // table selector, column
Sven van de Scheur
  • 1,809
  • 2
  • 15
  • 31