“动态创建的表”上的复选框(每行最多只能选择1个)

Checkboxes on Dynamically Created Table (only 1 selected max per row)

本文关键字:选择 1个 创建 动态 复选框      更新时间:2023-09-26

我有一个动态创建的表,每个表行有三个复选框。我想做的是每个表行只有一个复选框。因此,如果用户选中了一个复选框,并单击了同一行中的另一个复选复选框,则会取消选中上一个框并选中当前单击的框。我有以下代码:

$('.classCheckboxOne').on 'change', ->
  if $('.classCheckboxOne').prop('checked')
    $('.classCheckboxTwo').prop('checked', false)
    $('.classCheckboxThree').prop('checked', false)
$('.classCheckboxTwo').on 'change', ->
  if $('.classCheckboxTwo').prop('checked')
    $('.classCheckboxOne').prop('checked', false)
    $('.classCheckboxThree').prop('checked', false)
$('.classCheckboxThree').on 'change', ->
  if $('.classCheckboxThree').prop('checked')
    $('.classCheckboxTwo').prop('checked', false)
    $('.classCheckboxOne').prop('checked', false)

因此,这段代码适用于表的第一行,但其他表将无法正常工作。我所知道的处理此类问题的唯一其他方法是使用id而不是类名,但这对我的情况不起作用,因为表是动态创建的,因此会有多行的表元素包含相同的id。因此,我的问题是如何使上述功能在我的每一个表行上都起作用。非常感谢。

通常这就是HTML单选按钮的作用。只需确保同一组中的按钮有一个唯一的名称,可能是一个id和表的行号。

<input type="radio" name="x" value="one" checked> One
<input type="radio" name="x" value="two"> Two
<input type="radio" name="x" value="three"> three 
<hr />
<input type="radio" name="y" value="one" checked> One
<input type="radio" name="y" value="two"> Two
<input type="radio" name="y" value="three"> three 
<hr />
<input type="radio" name="z" value="one" checked> One
<input type="radio" name="z" value="two"> Two
<input type="radio" name="z" value="three"> three 

但是,如果您想使用复选框,请为每行的所有复选框指定一个类名。然后你可以做这样的事情。

// Checkbox onclick function
function selectOneInRow(event) {
  // Get all checkboxes with same classname 
  // as the one you just clicked
  var nodes = document.querySelectorAll('.' + event.target.className);
  // deselect all with same class
  for(var i = 0; i < nodes.length; i++) {
    nodes[i].checked = false
  }
  // but select the one you clicked
  event.target.checked = true;
}
// Just code to generate checkboxes
var el = document.getElementsByTagName("body")[0];
var checkboxes = 3;
var rows = 5;
function createCheckbox(rowNumber) {
  var input = document.createElement('input')
  input.type = 'checkbox';
  input.className = 'checkbox-' + rowNumber;
  input.onclick = selectOneInRow;
  return input;
}
for (var i = 0; i < rows; i++) {
  for (var j = 0; j < checkboxes; j++) {
    el.appendChild(createCheckbox(i))
  }
  el.appendChild(document.createElement('hr'));
}

试试这个

$(document).ready(function(){
  $('.groupCheck').change(function(){
    $('.groupCheck').not( $(this) ).prop( 'checked', false );
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" width="100%">
<tr>
  <td><input type="checkbox" class="groupCheck" name="post_id" value="1"/></td>
</tr>
<tr>
  <td><input type="checkbox" class="groupCheck"  name="post_id" value="2"/></td>
</tr>
<tr>
  <td><input type="checkbox" class="groupCheck"  name="post_id" value="3"/></td>
</tr>
</table>