views:

43

answers:

3

using jquery I need to retrieve an array from table cells, format the data and pass it into a js function.

the code i am using is this:

 var l1 = new Array();
   $('table#datatable tbody td:first-child').each(function() {
   l1.push($(this).text());
   });

this is the table fragment

  <tr>
               <th scope="row">Age: 0-4</th>
               <td>0</td>
               <td>9.7</td>
           </tr>
           <tr>
               <th scope="row">5-17</th>
               <td>23.6</td>
               <td>18.0</td>
           </tr>
           <tr>
               <th scope="row">Total 0-17</th>
               <td>20.6</td>
               <td>16.1</td>
           </tr>

the table's id is "datatable". i want to return an array of the contents of each first td and then format it like this: 0,23.6,20.6

i am very new to using arrays...

+1  A: 

This should work:

var values = [];
$('#datatable tbody tr').each(function () {
    values.push($('td:first', this).text());
});
console.log(values);

Explanation:

  • Line 1: create the values variable and set it to an empty array.
  • Line 2: loop over every tr in #datatable.
  • Line 3: add the text of the first td in the tr to the values array.
  • values is now populated with the values.
moff
This will add the text for all the `td` elements, not just the first one.
interjay
No, it won't - `.text()` will grab the first element automatically.
moff
@moff - That is *not* correct, your result is: `["09.7", "23.618.0", "20.616.1"]`...see for yourself: http://jsfiddle.net/EUUjP/ Read the description for `.text()`: http://api.jquery.com/text/ "Get the **combined text** contents of each element in the set of matched elements, including their descendants."
Nick Craver
Ahh, sorry. I've updated my post.
moff
+1  A: 

You can do this:

var l1 = $('#datatable td:nth-child(2)').map(function() {
  return $(this).text();
}).get();
//l1 = [0, 23.6, 20.6]

See here for a demo

This uses .map() to get an array from the elements. Your main problem is that :first-child needs to be the first child of the parent, it doesn't mean the "first child of this type", so only a <th> would be :first-child in your code. Instead you need the 2nd child, or :nth-child(2) to get the first <td> element.

Nick Craver
DOH, i didnt realize that the TH counted as part of the set. this worked beautifully thanks. i am trying to create a plugin for jqPlot that converts tables to charts.
liz
@liz - Ah I thought I recognized that markup, glad this worked you you. +1 on the question, asked exactly as it should be: including what you tried and the expected result, the markup/code is a huge plus and make the question much easier to answer, kudos.
Nick Craver
thanks :-) slowly learning...
liz
+1  A: 

td:first-child won't match anything because none of the <td> elements are the first children (they are preceded by <th>). Instead, use td:nth-child(2).

interjay