首页 > 解决方案 > 将类添加到禁用复选框

问题描述

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

如何正确地将“红色”类添加到禁用的输入,然后在 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>

标签: javascriptjquery

解决方案


使用您当前的代码并进行小的更正(例如使用兄弟选择器),您将获得:

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>


推荐阅读