[英]Getting data from a specific column in a HTML table when a checkbox in that row is checked using Javascript/JQuery
我有一個包含5列的HTML表。 第一列是一個復選框。 我想在選中該行中的復選框時找到第5列(最后一列)的內容。
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>
我是javascript的初學者,但嘗試過這樣做。
** JS:**
$(document).ready(function(){
if($('input.chk').is(':checked')){
var y = $("td:nth-of-type(5)").html();
alert(y);
}
});
此函數僅返回第一行,即選中復選框時,它顯示“D1的數據”。 但我想要所有的行。
謝謝你的幫助。 :)
請嘗試一次:
$(".chk").on("change", function(){
var y = $(this).parent().parent().find('td').eq(4).html();
alert(y);
});//
如果只有選中復選框才要執行此代碼,則可以添加:checked
condition。
另一種方法是基於使用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>
請試試這個
$(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);
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.