Question

I have a table and I'm retrieving each table row by doing this:

$(function(){
        $('table tr').click(function(){
            var $row = $(this).html();
            alert($row);
        });
    });

This gets me the current row like this:

<td>2</td>
<td>Malcriado</td>
<td>Bota</td>
<td>Tipo2</td>
<td>NuevaDesc</td>
<td>NuevaDesc</td>
<td></td>
<td>Cerdo</td>
<td>Azul</td>
<td>oso</td>
<td>Rojo</td>
<td>12</td>
<td>metal</td>
<td>sss</td>
<td></td>
<td>Delicias</td>

What I am trying to accomplish next is to remove the td's and get the values in between and get them into an array, but I haven't been able to accomplish this. Any ideas?

Was it helpful?

Solution

Use the children()(docs) method to get the <td> elements, then the map()(docs) method to create an Object containing the values, and finally the toArray()(docs) method to convert it into an Array.

$('table tr').click(function(){
    var values = $(this).children('td').map(function() {
        return this.innerHTML;
    }).toArray();

    alert(values);
});

OTHER TIPS

$(function() {
    $('table tr').click(function() {
        var arr = [];
        $('td', this).each(function(i, item) {
            if (item.innerHTML) 
              arr.push(item.innerHTML);
        });
        alert(arr.join(','));
    });
});

jast for sake added check for empty <TD>

Iterate over the elements in the row and get their text:

var contentArray = [];
$("td", $row).each(function(){
  contentArray.push($(this).text());
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top