我正在进行一个项目,我必须在表格中显示复选框及其值。这意味着在一个列中,复选框将存在,而下一列我必须显示其值。我是jquery
的新手,所以我试过但没有得到正确的输出。
$('input[type=checkbox]').on('change', function() {
if ($(this).is(':checked')) {
var values = [];
$.each($('input:checked'), function(index, input) {
values.push(input.value);
});
var str = values.join(',');
$(".hello").html(str);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>checkboxes</th>
<th>Values</th>
</tr>
<tr>
<td>
<input type="checkbox" name='cbox' value="red" class="theClass" />red
</td>
<td class="hello"></td>
</tr>
<tr>
<td>
<input type="checkbox" name='cbox' value="green" class="theClass" />green
</td>
<td class="hello"></td>
</tr>
<tr>
<td>
<input type="checkbox" name='cbox' value="blue" class="theClass" />blue
<p></p>
</td>
<td class="hello"></td>
</tr>
</table>
<table>
您将值设置为具有类hello
的所有表格单元格。您应该只选择复选框旁边的那个。你可以通过navigating to the parent cell和next cell来做到这一点。
一种方法是$(this).parent().next(".hello")
EG
$('input[type=checkbox]').on('change', function() {
var val = this.checked ? this.value : "";
$(this).parent().next(".hello").text(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>checkboxes</th>
<th>Values</th>
</tr>
<tr>
<td>
<input type="checkbox" name='cbox' value="red" class="theClass" />red
</td>
<td class="hello"></td>
</tr>
<tr>
<td>
<input type="checkbox" name='cbox' value="green" class="theClass" />green
</td>
<td class="hello"></td>
</tr>
<tr>
<td>
<input type="checkbox" name='cbox' value="blue" class="theClass" />blue
<p></p>
</td>
<td class="hello"></td>
</tr>
</table>
<table>