In a <table>
with check box in the Last column, on selection of whcih I want to sum the values of previous two <td>
.
The js
function should sum the values of the columns for which the CheckBox
is ticked
. But I am stuck at locating the previous <td>
itself. The Snippet is as follows.
function doSumAeFunction(){
var prevCell = $(this).closest('tr').prev('td').text();
console.log(prevCell);
alert(prevCell);
}
table {
table-layout: fixed;
width: auto;
border-collapse: collapse;
border: 3px solid purple;
}
table,
th,
td {
border: 1px solid;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<table style="table table-bordered text-center" style="width:auto">
<thead>
<th>Sl No</th>
<th>English</th>
<th>Geography</th>
<th>Maths</th>
<th>Science 2</th>
<th align="center">Select</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>22</td>
<td>15</td>
<td>12</td>
<td>15</td>
<td><input type="checkbox" value="checked" onclick="doSumAeFunction()" /></td>
</tr>
<tr>
<td>1</td>
<td>8</td>
<td>7</td>
<td>10</td>
<td>5</td>
<td><input type="checkbox" value="checked" onclick="doSumAeFunction()" />
</tr>
</tbody>
</table>
<br />
<div>
<div>Sum of Marks</div>
<div id="sum_of_maths">Sum of Maths is: </div>
<div id="sum_of_science">Sum of Science is: </div>
</div>
CodePudding user response:
To get the value in the cell before the checkbox use $(this).parent().prev('td').text()
:
$('input[type="checkbox"]').change(function() {
var prevCell = $(this).parent().prev('td').text();
console.log(prevCell);
})
table {
table-layout: fixed;
width: auto;
border-collapse: collapse;
border: 3px solid purple;
}
table,
th,
td {
border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<table style="table table-bordered text-center" style="width:auto">
<thead>
<th>Sl No</th>
<th>English</th>
<th>Geography</th>
<th>Maths</th>
<th>Science 2</th>
<th align="center">Select</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>22</td>
<td>15</td>
<td>12</td>
<td>15</td>
<td><input type="checkbox" value="checked" /></td>
</tr>
<tr>
<td>1</td>
<td>8</td>
<td>7</td>
<td>10</td>
<td>5</td>
<td><input type="checkbox" value="checked" />
</tr>
</tbody>
</table>
<br />
<div>
<div>Sum of Marks</div>
<div id="sum_of_maths">Sum of Maths is: </div>
<div id="sum_of_science">Sum of Science is: </div>
</div>