这里的问题是,我已经成功编写了用于添加和删除选中复选框中的行的代码,但它仅适用于第一个元素。
就像当我单击第一个元素时,它添加一行并在取消选中它时第二次删除该行,而当我选中并取消选中第二个复选框时,它在选中时添加一行,而在未选中时删除一行。
这是jquery代码
<script type="text/javascript">
$(document).ready(
function () {
$('.finding').change(
function () {
if ($('.finding').is(':checked')) {
var finding = $(this).next('label').text();
$('#findings-table').append("<tr><td>"+finding+"</td></tr>");
}
else {
$('#findings-table').empty();
}
});
});
</script>
这是我正在获得复选框的php代码
if ($checkResult > 0) {
for ($i=0; $i < $checkResult ; $i++) {
$result = mysqli_fetch_assoc($query);
$findings = $result['name'];
$count = 1 + $i;
echo"<tr>
<th scope='row'>$count</th>
<td scope='col'>
<div class='input-group'>
<input class='finding form-check-input' type='checkbox' name='findings[]' value='$findings'>
<label class='input-label pt-1 px-3'>$findings</label>
</div>
</td>
</tr>";
}
}
最后是出现复选框的我的html代码
<div class='table-container' style="height: 21vh;">
<table class="table table-hover" style="line-height: 7px;">
<tbody>
<?php include 'getfindings.php'; ?>
</tbody>
</table>
</div>
答案 0 :(得分:0)
我不知道什么是#findings-table,因此我刚刚创建了一个表。
看到这个:
$(function() {
$('.finding').on('change', function(e) {
var $this = $(e.currentTarget),
$findingTable = $('#findings-table'),
labelText = $this.parents('.input-group').find('.input-label').text();
if ($this.is(':checked')) {
$findingTable.append($('<tr/>').append($('<td/>').text(labelText)));
} else {
$findingTable.empty();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table id="findings-table"></table>
<div class='table-container' style="height: 21vh;">
<table class="table table-hover" style="line-height: 7px;">
<tbody>
<tr>
<th scope='row'>1</th>
<td scope='col'>
<div class='input-group'>
<input class='finding form-check-input' type='checkbox' name='findings[]' value='a'>
<label class='input-label pt-1 px-3'>nice a</label>
</div>
</td>
</tr>
<tr>
<th scope='row'>2</th>
<td scope='col'>
<div class='input-group'>
<input class='finding form-check-input' type='checkbox' name='findings[]' value='b'>
<label class='input-label pt-1 px-3'>nice b</label>
</div>
</td>
</tr>
<tr>
<th scope='row'>3</th>
<td scope='col'>
<div class='input-group'>
<input class='finding form-check-input' type='checkbox' name='findings[]' value='c'>
<label class='input-label pt-1 px-3'>nice c</label>
</div>
</td>
</tr>
<tr>
<th scope='row'>4</th>
<td scope='col'>
<div class='input-group'>
<input class='finding form-check-input' type='checkbox' name='findings[]' value='d'>
<label class='input-label pt-1 px-3'>nice d</label>
</div>
</td>
</tr>
</tbody>
</table>
</div>