如果一个复选框被选中,如何取消另一个复选框?
问题描述:
我有一些问题,我的计算器,我有五个复选框(costOne,costTwo,costThree,costFour,costFive)如果一个复选框被选中,如何取消另一个复选框?
当我检查costOne,然后costTwo应该关闭,但如果我点击这个costTwo(然后关闭)然后costOne应该关闭。
我的代码工作只是部分:当我点击costOne,那么你就不能在costTwo点击了(因为它被禁用),但是当我点击costOne它关闭,costTwo同时打开 - 这正是我想要的。我不能点击costTwo。
第一个和第三个输入我需要有这个链接的行为。
下面是相关代码:
//calculator
var init = $('.switch input').on('click', function() {
var value1 = 0;
var value2 = 0;
var costOne = $("#cost-one"),
costTwo = $("#cost-three");
if (costOne.is(':checked')) {
costOne.prop("checked", true);
costTwo.prop("checked", false);
} else {
costOne.prop("checked", false);
costTwo.prop("checked", true);
}
init.filter(':checked').closest('tr').each(function() {
value1 += (+$(this).find('span.cost-one').text());
value2 += (+$(this).find('span.cost-two').text());
});
$('.counter-one span').eq(0).html(value1 + ' ');
$('.counter-two span').eq(0).html(value2 + ' ');
});
答
您可以使用此代码(简化为重点考虑的问题):
$('input').on('change', function(){
var id = $(this).prop('id');
if (id == 'cost-one' || id == 'cost-three') {
// Make sure the two have opposite values:
var other = id == 'cost-one' ? 'cost-three' : 'cost-one';
$('#'+other).prop("checked", !$(this).prop("checked"));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
One: <input type="checkbox" id="cost-one"><br>
Two: <input type="checkbox" id="cost-two"><br>
Three: <input type="checkbox" id="cost-three" checked><br>
的其他变量将确定其他复选框的ID:如果你点击成本一个,将参考成本三,反之亦然。
然后,其他复选框将得到相反的选中状态。
为了保持一致,您还应该在页面加载时检查其中的一个,因此我添加了第三个复选框的checked
属性。
正如评论中所表达的那样,这种行为对于单选按钮是标准的。因此,除非你的图书馆不支持相同的窗口小部件 - 你可以更好地使用它们(对于那些链接的项目)。
答
刚刚与这个jQuery尝试
<script>
$(document).ready(function(e) {
$('.example').on('change', function() {
$('.example').not(this).prop('checked', false);
});
});
</script>
<input class="example" type="checkbox" name="ny">
<input class="example" type="checkbox" name="bos">
<input class="example" type="checkbox" name="sfo">
<input class="example" type="checkbox" name="dc">
答
单选按钮已经做到这一点本身,作为意见建议:
<input type=radio name="a">
<input type=radio name="a">
只要使用相同的name
属性。
如果你想允许取消选中,使用此:
var checked;
$('[name="a"]').on('click', function() {
if(checked === this) {
checked = this.checked = false;
} else {
checked = this;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=radio name="a">
<input type=radio name="a">
为什么不使用单选按钮代替复选框? - 从我读到的问题中,它会给你想要的效果 - 除非我误解了你的规范的一部分。 –
这两个选项是否可能未被检查? – trincot
禁用表示禁用;它无法接收用户输入...可能是标题误导! – PeterKA