我建立了一个四行八列的表格,每列都有一个复选框。我希望每行只允许检查一个复选框。我正在尝试使用 jquery 来执行此操作。从逻辑上讲,它在 jsfiddle 中有效,但对我来说在本地不起作用。我确实首先使用了警报来确保首先加载 jQuery。
下面是我的代码。问题是,我仍然可以在每行中选中多个复选框,而我应该只允许选中一个复选框:
<body>
<h2>Checkbox Test</h2>
<script type="text/javascript" src="http://localhost/mytesting/jquery-2.1.4.js"></script>
<script type="text/javascript">
function onLoadAlert() {
alert('Sup');
}
$(document).ready(onLoadAlert);
</script>
<script type="text/javascript">
$('input[type="checkbox"]').on('change', function() {
// uncheck sibling checkboxes (checkboxes on the same row)
$(this).siblings().prop('checked', false);
// uncheck checkboxes in the same column
$('div').find('input[type="checkbox"]:eq(' + $(this).index() + ')').not(this).prop('checked', false);
});
</script>
<table border="1">
<tbody>
<tr>
<th><b>COST</b></th>
<th colspan="3">Reduced Cost</th>
<th>Neutral</th>
<th colspan="3">Increased Cost</th>
<th>Don't Know</th>
</tr>
<tr>
<th></th>
<th>High</th>
<th>Medium</th>
<th>Low</th>
<th>No effect</th>
<th>Low</th>
<th>Medium</th>
<th>High</th>
<th></th>
</tr>
<tr>
<td>Capital cost</td>
<div>
<td><input type="checkbox" id="matrix1" value="1"></td>
<td><input type="checkbox" id="matrix2" value="1"></td>
<td><input type="checkbox" id="matrix3" value="1"></td>
<td><input type="checkbox" id="matrix4" value="1"></td>
<td><input type="checkbox" id="matrix5" value="1"></td>
<td><input type="checkbox" id="matrix6" value="1"></td>
<td><input type="checkbox" id="matrix7" value="1"></td>
<td><input type="checkbox" id="matrix8" value="1"></td>
</div>
</tr>
</tbody>
最佳答案
您的 input
元素不是 sibling ,因为它们有不同的父元素 – td
元素:
<td><input type="checkbox" id="matrix1" value="1"></td>
<td><input type="checkbox" id="matrix2" value="1"></td>
这就是为什么这不起作用:
$(this).siblings().prop('checked', false);
相反,这样做:
$(this).closest('tr').find('input').not(this).prop('checked', false);
或者,您可以使用具有相同
name
的单选按钮:
<td><input type="radio" name="matrix"></td>
<td><input type="radio" name="matrix"></td>
<td><input type="radio" name="matrix"></td>
这样,您就不需要任何 JavaScript。
关于javascript - jQuery 不适用于只选择一个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30248846/