I have a HTML table with 5 columns. The first column is a checkbox. I want to find the content of the 5th column (last column) when the checkbox in that row is checked.
HTML :
<table>
<tr>
<th></th>
<th>A</tr>
<th>B</tr>
<th>C</tr>
<th>D</tr>
</tr>
<tr>
<td><input type='checkbox' class="chk" /></td>
<td>data for A1</td>
<td>data for B1</td>
<td>data for C1</td>
<td>data for D1</td>
</tr>
<tr>
<td><input type='checkbox' class="chk"/></td>
<td>data for A2</td>
<td>data for B2</td>
<td>data for C2</td>
<td>data for D2</td>
</tr>
</table>
I am a beginner in javascript but have tried doing this.
**JS : **
$(document).ready(function(){
if($('input.chk').is(':checked')){
var y = $("td:nth-of-type(5)").html();
alert(y);
}
});
This function returns only for the first row ie when the checkbox is checked it shows "data for D1". But I want it for all the rows.
Thanks for your help. :)
Please try this once:
$(".chk").on("change", function(){
var y = $(this).parent().parent().find('td').eq(4).html();
alert(y);
});//
You can add :checked
condition if you want to execute this code only if the checkbox is checked.
A different approach is based on using eq :
$(function () { $(':checkbox').on('click', function(e) { if (this.checked == true) { var fifthEle = $(this).parent().siblings().eq(3); $('#logMsg').append('<p>' + fifthEle.text() + '</p>'); } }) });
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script> <table> <tr> <th></th> <th>A <th>B <th>C <th>D </tr> <tr> <td><input type='checkbox' class="chk"/></td> <td>data for A1</td> <td>data for B1</td> <td>data for C1</td> <td>data for D1</td> </tr> <tr> <td><input type='checkbox' class="chk"/></td> <td>data for A2</td> <td>data for B2</td> <td>data for C2</td> <td>data for D2</td> </tr> </table> <div id="logMsg"></div>
Please try this one
$(document).on('click','input.chk',function(){
// getting the tds with in the rows in which check exists
$tds=$(this).parent().siblings();
if($(this).is(':checked'))
{
$data=$($tds[$tds.length-1]).text();
alert($data);
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.