如何在每个表行中单击a标记时选中复选框

How to check checkbox when a-tag is clicked in each table row?

本文关键字:复选框 单击      更新时间:2023-09-26

我使用的是较旧版本的jquery。我当前的代码只适用于表的第一行。如果我把它切换到一个类而不是一个ID,它会检查每一行。我需要它单独处理每一行。

Jquery代码:

$('#enableCheckbox').click(function(){
    $('#checkbox').attr("checked", true);
})

HTML:

<td><a href="pdfview.cfm?id=#hardwareid#" target="_blank" id="enableCheckbox">Create</a></td>
<td><input type="checkbox" name="checkbox" id="checkbox"></td>

您希望在每次单击标记时选中复选框,因此不要给标记id,因为它只适用于第一个id。

请看下面的代码,我想它会对你有所帮助。

$(document).ready(function(){
$("table tr td a").click(function (e) {
          $(this).parent().next().find('input').attr("checked", true);
  //If you want to check and uncheck on click then follow below code
  //$(this).parent().next().find('input').attr("checked", !$(this).parent().next().find('input').attr("checked"));
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<table>
  <tr>
    <td><a href="#" target="_blank">Create</a></td>
<td><input type="checkbox" name="checkbox" id="checkbox"></td>
    </tr>
  <tr>
    <td><a href="#" target="_blank">Create</a></td>
<td><input type="checkbox" name="checkbox" id="checkbox"></td>
    </tr>

id在一个表上必须是唯一的,所以不能对表的每一行使用相同的id,因为大多数浏览器只会返回具有id的第一个元素(这就是为什么只获得表的第一行)。

您可以做的是,您可以为您提到的类设置事件侦听器,但也可以为表行设置唯一的数据元素。

或者,如果您在后续表格单元格中没有其他输入,您可以使用以下代码:

$('.enableCheckbox').on("click", function(event){
   var $input = $(event.target).parent().find("input");
   $input.prop("checked", true);
});