如果选中复选框并选择了选项,则删除禁用的类jQuery

时间:2018-02-01 15:45:29

标签: javascript jquery html html5

我正试图通过jQuery获得条件,但是没有获得成功。我想如果选中复选框并选择了选项,则从锚点按钮中删除禁用的类。

这是我的代码

$(document).ready(function() {
  $("#limitation").change(function() {
    if ($("#child-limit").is(':checked') == "true" && $("#piller").val()) {
      $("#limitation").removeClass("disabled");
    } 
  else if ($("#child-limit-1").is(':checked') == "true" && $("#piller-2").val()) && $('input[name=gender]:checked').val() == "yes") {
       $("#limitation").removeClass("disabled");
 }
  else {
      $("#limitation").addClass("disabled");
    }
  });
  $("#limitation").change();
});
.disabled {
  background: #cdc8c7;
  pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input autocomplete="off" type="checkbox" name="checkbox-limit" id="child-limit" />
<select id="piller" name="firstpillers" class="select">
      <option value="" class="placeholder" selected disabled>Make choice</option>
      <option value="0">0</option>
      <option value="1">1 </option>
      <option value="2">2</option>                                 
    </select>

<a href="#" id="limitation" class="btn disabled">Volgende stap</a>

当我只检查这样的选择条件时,此代码工作正常。

$(document).ready(function() {
  $("select").change(function() {
    if ($("#piller").val()) {
      $("#limitation").removeClass("disabled");
    } else {
      $("#limitation").addClass("disabled");
    }
  });
  $("select").change();
});

2 个答案:

答案 0 :(得分:1)

您已将处理程序分配给错误的元素

此外,您使用字符串.is(':checked') == "true"测试布尔值是否相等,这是错误的(并且无需测试)

我可能会像这样编码

function enableLink() { // test value is selected AND checkbox is checked
  var ok = $("#piller").val() != "" &&  $("#child-limit").is(':checked');
  $("#limitation").toggleClass("disabled",!ok); // disable if false
}
$(document).ready(function() {
  $("#piller").on("change",enableLink).change(); // run on change and run change on load
  $("#child-limit").on("click",enableLink); // run on click
});
.disabled {
  background: #cdc8c7;
  pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input autocomplete="off" type="checkbox" name="checkbox-limit" id="child-limit" />
<select id="piller" name="firstpillers" class="select">
      <option value="" class="placeholder" selected disabled>Make choice</option>
      <option value="0">0</option>
      <option value="1">1 </option>
      <option value="2">2</option>                                 
    </select>

<a href="#" id="limitation" class="btn disabled">Volgende stap</a>

添加更多条件

var ok = ($("#piller").val()   != "" && $("#child-limit").is(':checked')) ||
         ($("#piller-2").val() != "" && $("#child-limit-1").is(':checked') &&
          $('input[name=gender]:checked').val() == "yes"));

答案 1 :(得分:-1)

检查条件.. == true代替==&#39; true&#39;