Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through table cells with jQuery and send the data to database

Tags:

jquery

ajax

loops

What's the best method for looping through a table, grabbing all the data in the cells, but skipping the <th>? Do I put the data in an array?

like image 328
Matt Avatar asked Feb 26 '10 19:02

Matt


1 Answers

Say you have a table that looks like this:

<table>
    <tr>
        <td>Information 1</td>
        <td>Information 2</td>
    </tr>
</table>

You could do something like this:

var cells = new Array();
$("table td").each(function(){
   cells.push($(this).html());
});

What exactly are you looking to do with the data?


The easiest thing to do to skip the headers would to just remove them from the array after the loop is done.

After the code is done, you can run something like this:

cells = cells.slice(1, cells.length);

This will set the array to a copy of itself, minus the first element.

Alternatively, when you initially loop through it, only store the information if the index is greater than zero:

var cells = new Array();
$("table td").each(function(index){
   if(index > 0){
      cells.push($(this).html());
   }
});

And finally, if you'd like to go with a more traditional javascript solution that does not require a condition:

var cells = new Array();
for(index = 1; index < $("table td").length; index++){
   cells.push($("table td").get(index).html());
};

That way, you're starting from the second row.

like image 61
Yuval Karmi Avatar answered Sep 20 '22 23:09

Yuval Karmi