Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery conditional selector for table rows

I have a table with data in:

<td> item </td><td> order code </td><td> price </td>

I'm processing the table with jQuery which needs to find the order code:

$.each($('.productList tbody tr'), function() {
    var orderCode = $(this).find('td:eq(1)').html().trim();
    // do stuff
});

If there are no products, the table shows a message:

<td colspan="3"> There are no products to display </td>

The above row causes the jQuery function to bomb out. What's the most robust way to use a conditional selector to ignore the "no products" row? Is there a selector for colspan="1" or colspan is not set or whatever it would need to be?

like image 905
fearofawhackplanet Avatar asked Jul 19 '10 13:07

fearofawhackplanet


3 Answers

Like this:

$('.productList tbody tr:has(td:nth-child(2))').each(function() {
    ...
});

This will only select <tr> elements that have a <td> that is the second child of its parent. (the nth-child selector is one-based)

like image 150
SLaks Avatar answered Oct 12 '22 20:10

SLaks


Don't refine your selector, it won't scale well because jQuery will have to evaluate every child element. Avoid the error instead...

$('.productList tbody tr').each(function() { 
   var orderCode = $(this).find('td:eq(1)');

   if(orderCode.length > 0) { // Make sure it exists
     orderCode = orderCode.html().trim(); 
     // do stuff 
   }
}); 
like image 37
Josh Stodola Avatar answered Oct 12 '22 20:10

Josh Stodola


If you can change how you generate the table, using classes is a cleaner solution:

<td class="item-name"> item </td>
<td class="order-code"> order code </td>
<td class="item-price"> price </td>

Then select only the desired class:

var orderCode = $(this).find('td.order-code').html().trim();
if(orderCode)
{
  //do stuff
}

This will also give you increased flexibility in styling the table with CSS, and your code won't break if you add or reorder columns.

like image 24
Kip Avatar answered Oct 12 '22 20:10

Kip