sm1l3y sm1l3y - 4 months ago 10
Javascript Question

JQuery - search through column, when text changes add new row before

I am looking for a dynamic method of searching through a column and when a value changes a new row should be inserted.

Consider the following table:

<table id="testTable">
<tbody>
<tr>
<th>Letter</th>
<th>Amount</th>
</tr>
<tr>
<td class="parent">A</td>
<td>110</td>
</tr>
<tr>
<td class="parent">A</td>
<td>99</td>
</tr>
<tr>
<td class="parent">A</td>
<td>106</td>
</tr>
<tr>
<td class="parent">A</td>
<td>120</td>
</tr>
<tr>
<td class="parent">C</td>
<td>103</td>
</tr>
</tbody>
</table>


When it encounters a change such as going from 'A' to 'C' in the parent class, I would like a row inserted before 'C' or whatever value maybe different from the one before. I have sort of started with this to capture some data but have not gotten far:

$('#' + value + ' .parent').each(function () {
var firstVal = $(this).html();
var secondVal = $(this).next().html();
if(firstVal == secondVal) {
}
else {
$(this).parent().after('</tr><tr><td class="sub0">Sub Total</td></tr>');
}
})


Please see my JSFiddle

Answer
$(document).ready(function(){
var lastVal = '';
$('#testTable .parent').each(function () {
        var currentVal = $(this).html();
        if(currentVal != lastVal) {
            $(this).parent().before('</tr><tr><td class="sub0">Sub Total</td></tr>');
            lastVal = currentVal;
        }
    });
});

Fiddle

Comments