选中是否启用基于复选框的按钮

时间:2018-05-16 10:32:49

标签: javascript jquery html

当我没有选中任何复选框时,我一直面临一个问题,那么按钮不会被禁用,它仍然启用。

我还将属性设置为禁用按钮,但仍然启用;

这是我的代码

<input class="form-check-input tab1_chk" type="checkbox" name="2[]"  value="1">Option 1

<input class="form-check-input tab1_chk" type="checkbox" name="2[]"  value="2">Option 2

<input class="form-check-input tab1_chk" type="checkbox" name="2[]"  value="2">Option 3
<br>
<br>
<button type='button' class='tab1_btn' name="next" id="next">              
    Next       
</button>
if ($(".tab1_chk:checked" )) {
  $('.tab1_btn').prop('disabled', false);
} else {
  $('.tab1_btn').prop('disabled', true);
}

当我在此$('.tab1_btn').prop('disabled', false);

之前发出提醒时

然后警报在运行时显示,但在此$('.tab1_btn').prop('disabled', true);之前发出警报2,然后警报未显示第一个警报显示

JSFiddle

我需要在没有选中任何复选框的情况下,然后禁用下一个按钮

4 个答案:

答案 0 :(得分:2)

您需要应用事件处理程序

$('.tab1_btn').prop('disabled', !$('.tab1_chk:checked').length);//initially disable/enable button based on checked length
$('input[type=checkbox]').click(function() {
    if ($('.tab1_chk:checkbox:checked').length > 0) {
        $('.tab1_btn').prop('disabled', false);
    } else {
        $('.tab1_btn').prop('disabled', true);
    }
});

工作代码段: - https://jsfiddle.net/bmpp663q/

答案 1 :(得分:1)

要完成这项工作,您需要检查当任何状态发生变化时是否有任何选中的复选框。

要执行此操作,您可以将change事件处理程序附加到它们,然后使用:checked选择器确定是否已选择任何事件,然后根据需要启用/禁用该按钮。试试这个:

&#13;
&#13;
$('.form-check-input').change(function() {
  $('#next').prop('disabled', !$('.form-check-input:checked').length);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
  <input class="form-check-input tab1_chk" type="checkbox" name="2[]" value="1">
  Option 1
</label>

<label>
  <input class="form-check-input tab1_chk" type="checkbox" name="2[]" value="2">
  Option 2
</label>

<label>
  <input class="form-check-input tab1_chk" type="checkbox" name="2[]" value="2">
  Option 3
</label><br /><br />

<button type="button" class="tab1_btn" name="next" id="next" disabled="true">Next</button>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

尝试以下代码为我工作:

$(document).ready(function(){
    checkboxDisable()

    $(".tab1_chk").click(function(){
    checkboxDisable();
  });


  function checkboxDisable(){
    if($(".tab1_chk:checked").length > 0)
    {
      $('.tab1_btn').prop('disabled', false);

    }else{
      $('.tab1_btn').prop('disabled', true);

    }
  }
});

答案 3 :(得分:0)

事件处理程序是一个很好的解决方案......喜欢它!如果您想在页面加载时执行此操作,可以通过对现有代码稍作更改来执行此操作,如:

if ($(".tab1_chk").is(':checked')) {
  $('.tab1_btn').prop('disabled', false);
} else {
  $('.tab1_btn').prop('disabled', true);
}

它有效,我用你的代码试了!!

相关问题