user1386654
user1386654

Reputation: 51

Store table data to a jquery variable

I want to store data in a table to a jquery variable, the code im using is as below, but this code is storing all table tags like tr, td and everything to the variable, where as i just need to store the data in td tag in text format to a jquery variable..can anyone help?

var table = $("#mytable").html();

Upvotes: 2

Views: 7865

Answers (4)

sharif2008
sharif2008

Reputation: 2798

try this :-

var header = Array();

$("#mytable tr th").each(function(i, v){
    header[i] = $(this).text();
})

alert(header);

var data = Array();

$("#mytable tr").each(function(i, v){
    data[i] = Array();
    $(this).children('td').each(function(ii, vv){
    data[i][ii] = $(this).text();
 }); 
})

alert(data);

Upvotes: 0

Miqdad Ali
Miqdad Ali

Reputation: 6147

var table_data;
$("#mytable td").each(function(){
   table_data += $(this).text();
});

console.log(table_data)

Upvotes: 0

Barmar
Barmar

Reputation: 780673

If you just want the text, use .text() instead of .html():

var table = $("#mytable").text();

Upvotes: 0

Balint Bako
Balint Bako

Reputation: 2560

You can collect the cell values like this:

arr = new Array();
$("td").each(function () {
    t = $(this).text();
    arr.push(t);
});

console.log(arr);

Upvotes: 1

Related Questions