我的计算器出了一些问题,我有五个复选框(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 + ' ');
});发布于 2016-08-18 11:47:34
您可以使用此代码(简化为关注此问题):
$('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属性。
正如在评论中所表示的,这种行为是单选按钮的标准行为。因此,除非您的库不支持相同的小部件--查找它,否则您可以更好地使用它们(对于那些链接的项)。
发布于 2016-08-18 11:16:43
只需尝试使用这个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">
https://stackoverflow.com/questions/39016642
复制相似问题