kobame
kobame

Reputation: 5856

Search the table by cell content with jquery and relative referencing

Having such table

<table>
<thead> ... </thead>
<tbody>
  <tr class="TableOdd">
    <td class="TableCol0"> 1 </td>
    <td class="TableCol1"> x </td>
    <td class="TableCol2"> x </td>
    <td class="TableCol3"> # </td>
  </tr>
  <tr class="TableEven">
    <td>....</td>
  </tr>
</tbody>

E.g. each cell has own class indicating it's column number TableCol0,1,2..N

In each row, needed compare the content of the cells in column 1 and 2 and write the result into colum3.

Managed the following script,

$(document).ready(function() {
var toterr = 0;
$('tbody tr.TableEven,tbody tr.TableOdd').each(function() {
    var wanted = $(this).find('.TableCol1' ).html();
    var actual = $(this).find('.TableCol2' ).html();
//console.log('wanted='+wanted+'=actual='+actual+'=');
    if ( wanted == actual ) {
        $(this).find('.TableCol3').text('ok');
    } else {
        $(this).find('.TableCol3').text('ERROR');
        toterr++;
    }
});
$('#totalerror').text(toterr);   
});

It is probably not optimal, but works.

Now have a bit different scenario: Need compare two cells what are before a cell with a specified content (:CMP:), e.g:

<table>
<thead> ... </thead>
<tbody>
  <tr class="TableOdd">
    <td class="TableCol0"> x </td>
    <td class="TableCol1"> x </td>
    <td class="TableCol2"> :CMP: </td>
    <td class="TableCol3"> etc </td>
  </tr>
  <tr class="TableEven">
    <td class="TableCol0"> N </td>
    <td class="TableCol1"> x </td>
    <td class="TableCol2"> y </td>
    <td class="TableCol3"> :CMP: </td>
  </tr>
</tbody>

For each row, need compare cells what are before :CMP:, and replace the :CMP: with the result. e.g.

I haven't idea how to modify the above script.

Upvotes: 0

Views: 51

Answers (1)

charlietfl
charlietfl

Reputation: 171679

Can easily get the index of the cell that contains ':CMP:' and use the index to reference the previous cells. Or use traverses like prev() or use eq() once index is found.

$('tbody tr').each(function () {
    var $cells = $(this).children(),
        $cmp = $cells.filter(':contains(":CMP:")'),
        cmpIndex = $cells.index($cmp);        
    // array of values of previous cells
    var values = $.map($cells.slice(cmpIndex - 2, cmpIndex), function (el) {
        return $.trim($(el).text());
    });
   // make sure we have 2 cells with values and compare
    var cmpText = values.length === 2 && values[0] === values[1] ? 'OK' : 'ERROR';
    $cmp.text(cmpText);
});

DEMO

Upvotes: 1

Related Questions