簡體   English   中英

是否根據復選框啟用和禁用按鈕

[英]Button enabled and disabled based on checkbox is checked or not

當未選中任何復選框時,我一直遇到一個問題,即該按鈕仍處於啟用狀態,因此不會被禁用。

我還將屬性設置為禁用按鈕,但仍然啟用;

這是我的代碼

<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', false);

然后將顯示警報何時運行,同時在$('.tab1_btn').prop('disabled', true);之前給出警報2 $('.tab1_btn').prop('disabled', true); 然后警報不顯示僅顯示第一個警報

的jsfiddle

我需要在未選中任何復選框的情況下禁用下一個按鈕

您需要應用事件處理程序

$('.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/

為了使這項工作有效,您需要檢查任何狀態更改時是否有任何選中的復選框。

為此,您可以將change事件處理程序附加到它們上,然后使用:checked選擇器確定是否已選擇任何一個,然后根據需要啟用/禁用按鈕。 嘗試這個:

 $('.form-check-input').change(function() { $('#next').prop('disabled', !$('.form-check-input:checked').length); }); 
 <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> 

嘗試下面的代碼為我工作:

$(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);

    }
  }
});

事件處理程序是一個很好的解決方案……喜歡它! 如果要在頁面加載時執行此操作,可以對現有代碼進行一些更改,例如:

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

它有效,我用您的代碼嘗試過!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM