Enable button when checkboxes selected

I have a few checkboxes and a submit button that is initially disabled. When checking the box, the button is turned on, and when you uncheck the box, the button is turned off again.

If several checkboxes are selected, but uncheck the button, the button will become inaccessible, even if I selected other checkboxes. How can I fix this problem?

<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> 
+6
source share
5 answers
 $(function() { $(".checkbox").click(function(){ $('.delete').prop('disabled',$('input.checkbox:checked').length == 0); }); }); 

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

+6
source

Try this when I basically check to see if all the checkboxes are checked, and then turn off the button.

 $(function() { $(".checkbox").click(function() { $(".delete").attr("disabled", !$(".checkbox:checked").length); }); }); 
+2
source

Implement a counter to track the number of checks, and not just turn off the button. Add 1 each time the field is checked, and subtract 1 each time the field is not checked. As soon as the counter reaches 0, disable the button. When it changes to 1, turn on the button (if it changes to any larger number, it will be turned on, so you do not need to turn it on every time). Example:

 <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> 
+2
source

You need to check the status of the remaining boxes each time window 1 is switched.

0
source

You can create an array of each flag. Then do the testing to check and exit the loop on the checkbox (this is what you care about). If you reach the end of the loop and verify that everything was false, disable the button.

This will prevent unchecking the button.

You are currently checking the "this" checkbox, not all.

0
source

Source: https://habr.com/ru/post/896517/


All Articles