gpt4 book ai didi

javascript - 将Class 添加到禁用复选框

转载 作者:行者123 更新时间:2023-11-28 17:23:45 26 4
gpt4 key购买 nike

我正在尝试使用复选框将Class添加到禁用的输入字段。但是,该类会应用于所有复选框,甚至是事件的复选框。

如何正确地将“红色”类添加到禁用的输入,然后在 MAX 小于 2 时删除该类。

var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
($('input.addnominee:checked').length == MAX) ? $('.checkmark').addClass('red'):$('checkmark').removeClass('red');
});
label {
display: block;
}
.checkmark.red {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<label class="checkbox"> Add Nominee
<input class="addnominee" type="checkbox">
<span class="checkmark">Hello</span>
</label>
<label class="checkbox"> Add Nominee
<input class="addnominee" type="checkbox">
<span class="checkmark">Hello</span>
</label>
<label class="checkbox"> Add Nominee
<input class="addnominee" type="checkbox">
<span class="checkmark">Hello</span>
</label>
<label class="checkbox"> Add Nominee
<input class="addnominee" type="checkbox">
<span class="checkmark">Hello</span>
</label>

最佳答案

使用您当前的代码并进行一些小的修正(例如使用 siblings selector ),您将得到:

var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled', true) : $('input.addnominee').not(':checked').attr('disabled', false);
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').siblings().addClass('red') : $('input.addnominee').siblings().removeClass('red');
});
label {display: block;}
.checkmark.red {color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkbox"> Add Nominee
<input class="addnominee" type="checkbox">
<span class="checkmark">Hello</span>
</label>
<label class="checkbox"> Add Nominee
<input class="addnominee" type="checkbox">
<span class="checkmark">Hello</span>
</label>
<label class="checkbox"> Add Nominee
<input class="addnominee" type="checkbox">
<span class="checkmark">Hello</span>
</label>
<label class="checkbox"> Add Nominee
<input class="addnominee" type="checkbox">
<span class="checkmark">Hello</span>
</label>

关于javascript - 将Class 添加到禁用复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52014394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com