我想从以下 html 中执行的是,当我单击复选框 2 时,我想查看复选框 1 是否被选中。
如果未选中复选框 1,我会收到警报
消息。否则,复选框
可以检查2个。
$('#table1').on('click',function(){
//code...
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="table1" border="1">
<tr>
<td>
<input type="checkbox" id="1" name="check" value="1"/><label>1</label>
</td>
<td>
<input type="checkbox" id="2" name="check" value="2"/><label>2</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="3" name="check" value="1"/><label>3</label>
</td>
<td>
<input type="checkbox" id="4" name="check" value="2"/><label>4</label>
</td>
</tr>
</table>
我对 jQuery 没有任何想法,因为我是一个新学习者。请帮助我。
最佳答案
你可以这样做:
$("#2").click(function() {
if ($("#1").prop("checked") == false ) {
alert("checkbox 1 is not checked");
$("#2").prop("checked", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1" border="1">
<tr>
<td>
<input type="checkbox" id="1" name="check" value="1" /><label>1</label>
</td>
<td>
<input type="checkbox" id="2" name="check" value="2" /><label>2</label>
</td>
</tr>
</table>
如果您还想在取消选中复选框 1 时取消选中复选框 2,您可以这样做:
$("#2").click(function() {
if ($("#1").prop("checked") == false ) {
alert("checkbox 1 is not checked");
$("#2").prop("checked", false);
}
});
$("#1").click(function() {
if ($(this).prop("checked") == false) {
$("#2").prop("checked", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1" border="1">
<tr>
<td>
<input type="checkbox" id="1" name="check" value="1" /><label>1</label>
</td>
<td>
<input type="checkbox" id="2" name="check" value="2" /><label>2</label>
</td>
</tr>
</table>
更新:该问题已编辑为现在有 2 行和 4 个复选框。
$("#2, #4").click(function() {
if ($(this).parent().prev().find("input").prop("checked") == false) {
let checkbox = $(this).parent().prev().find("input").attr("id");
alert("checkbox " + checkbox + " is not checked");
$(this).prop("checked", false);
}
});
$("#1, #3").click(function() {
if ($(this).prop("checked") == false) {
$(this).parent().next().find("input").prop("checked", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1" border="1">
<tr>
<td>
<input type="checkbox" id="1" name="check" value="1" /><label>1</label>
</td>
<td>
<input type="checkbox" id="2" name="check" value="2" /><label>2</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="3" name="check" value="1" /><label>1</label>
</td>
<td>
<input type="checkbox" id="4" name="check" value="2" /><label>2</label>
</td>
</tr>
</table>
关于jquery - 获取不同列中的复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61511377/