Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: enable submit when min 1 checkbox is checked

Tags:

jquery

How can I remove the "disabled='disabled' attribute of submit button with id='bla' if at least one checkbox with class='check' is checked?

If no checkboxes are checked, the disabled attribute should return to the submit button.

like image 456
stef Avatar asked May 01 '11 12:05

stef


2 Answers

EDIT (11-01-2021) - As pointed out by @Janus Bahs Jacquet, as of jQuery 1.6.1, properties of elements should be manipulated using the .prop() method instead of .attr() method.

$('.check').change(function() {
    if ($('.check:checked').length) {
        $('#sub').removeAttr('disabled');
    } else {
        $('#sub').props('disabled', true);
    }
});

Updated demo : http://jsfiddle.net/kjb0fyr8/


You just need to check the length property of the checked array

$('.check').change(function() {
    if ($('.check:checked').length) {
        $('#sub').removeAttr('disabled');
    } else {
        $('#sub').attr('disabled', 'disabled');
    }
});

Here's the demo : http://jsfiddle.net/LUnN5/

like image 72
JohnP Avatar answered Nov 11 '22 17:11

JohnP


Get a reference to all the checkboxes in question, and then on change() event, set the disabled property based on if any of the checkboxes are checked or not.

var checks = $(':checkbox.check');
checks.change(function() {
    $('#bla').attr('disabled', ! checks.filter(':checked').length);
});

jsFiddle.

like image 21
alex Avatar answered Nov 11 '22 17:11

alex