Enable button when checkboxes selected

2020-07-10 11:29发布

I have multiple checkboxes and a submit button that is initially disabled. When checking a box the button is enabled and when unchecking, the button is disabled again.

If have multiple checkboxes selected but uncheck one, the button becomes disabled even though I have selected other checkboxes. How can I fix this issue?

<script type="text/javascript"> 
$(function() {
    $(".checkbox").click(function() {
      $(".delete").attr("disabled", !this.checked);
    });
});
</script>

HTML

<input type="checkbox" name="msg[]" value="32" class="checkbox" />
<input type="checkbox" name="msg[]" value="44" class="checkbox" />
<input type="checkbox" name="msg[]" value="26" class="checkbox" />

<button type="submit" class="delete" disabled="disabled">Delete</button>

5条回答
地球回转人心会变
2楼-- · 2020-07-10 11:36

Try this where I am basically checking if all the checkboxes are not checked then disable the button.

$(function() {
    $(".checkbox").click(function() {
      $(".delete").attr("disabled", !$(".checkbox:checked").length);
    });
});
查看更多
beautiful°
3楼-- · 2020-07-10 11:38
$(function() {
    $(".checkbox").click(function(){
        $('.delete').prop('disabled',$('input.checkbox:checked').length == 0);
    });
});

Demo: http://jsfiddle.net/AlienWebguy/3U364/

查看更多
太酷不给撩
4楼-- · 2020-07-10 11:41

Implement a counter to track how many are checked, rather than just disabling the button. Add 1 every time a box is checked, and subtract 1 every time a box is unchecked. Once the counter hits 0, disable the button. When it changes to 1, enable the button (if it changes to any higher number it will have already been enabled, so you don't need to enable it every time). Sample:

<script type="text/javascript">
var boxcounter;
$(function() {
    boxcounter = 0;
    $(".checkbox").click(function() {
        if(this.checked) {
            counter++;
            if(counter == 1){
                $(".delete").attr("disabled", "");
            }
        } else {
            counter--;
            if(counter == 0){
                $(".delete").attr("disabled", "disabled");
            }
        }
    }
}
</script>
查看更多
闹够了就滚
5楼-- · 2020-07-10 11:53

You can build an array of every checkbox. Then, loop through testing for checked, and exit the loop on checked (this is what you care about). If you reach the end of the loop and checked for all was false, then disable the button.

This will prevent one uncheck from disabling the button.

You're currently only checking "this" checkbox rather than all.

查看更多
贪生不怕死
6楼-- · 2020-07-10 11:56

You need to check the state of the other boxes each time 1 box is toggled.

查看更多
登录 后发表回答