Jason Wysocki
Jason Wysocki

Reputation: 39

Javascript disabled button if checkboxes are not choosen - problem

I wrote a code, that make the button not disabled when you check at least one checkbox with class "sum".

I want to change the code, so I have to classes for and you can check only one checkbox (or two of them) to make the button not disabled.

This is what I have and it works with only one class:

 var checkBoxes = $('.sum');
checkBoxes.change(function () {
    $('#dashboardbuttonpay').prop('disabled', checkBoxes.filter(':checked').length < 1);
});
$('.sum').change();

    });

This is what I tried to do, but OR op does not work:

 var checkBoxes = $('.sum' || **'.checkAll'**);
checkBoxes.change(function () {
    $('#dashboardbuttonpay').prop('disabled', checkBoxes.filter(':checked').length < 1);
});
$('.sum'  || **'.checkAll'**).change();

    });

The code works with && operator, but I do not need this.

Upvotes: 2

Views: 58

Answers (3)

Suzy
Suzy

Reputation: 24

    var checkBoxes = $('.sum','.checkAll');
    checkBoxes.change(function () {
       if(checkBoxes.filter(':checked').length > 1)
           $('#dashboardbuttonpay').prop('disabled',true);
       else
           $('#dashboardbuttonpay').prop('disabled',false);
    });

Upvotes: 0

CoderLee
CoderLee

Reputation: 3479

You could check for the amount of checked inputs then add/remove the disabled property in the change event handler.

var checkBoxes = $('.sum','.checkAll');

checkBoxes.change(function () {
    if (checkBoxes.filter(':checked').length > 0) {
      $('#dashboardbuttonpay').prop('disabled', null);
    } else {
      $('#dashboardbuttonpay').prop('disabled');
    }
});

This way you capture if one or more checkboxes are checked before remove the disabled attribute of the button. Which lets you enable the button with either one or both checkboxes selected.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816404

Using the OR operation on strings this way does not make sense. If you do this with two non-empty strings, you always get the first operand:

console.log('a' || 'b')

In order to select multiple elements, you just separate them by comma:

var checkBoxes = $('.sum, .checkAll');

The code works with && operator, but I do not need this.

Not really. 'a' && 'b' always returns 'b'.

Upvotes: 5

Related Questions