cpt-crunchy cpt-crunchy - 3 months ago 19
CSS Question

Check box toggle option

I think I may be overthinking my problem.

I have 3 checkboxes using the bootstrap-toggle css. I have 3 checkboxes but
my condition is as such:

IF "Blue" and "Yellow" are checked, THEN "Green" will be checked and the other 2 will be unchecked. So long as "Green" is checked "Blue" and "Yellow" cant be checked. They don't need to disabled if "Green" is checked.
I would like use a javascript file unless this can be done in less code with Jquery. Open to either.

<div class="form-group">
<label for="blue">Blue
<input name="blue" class="button" type="checkbox" data-toggle="toggle" data-on="No" data-off="Yes" data-onstyle="default" data-offstyle="success">
</label>
</div>
<div class="form-group">
<label for="yellow">Yellow
<input name="yellow" class="button" type="checkbox" data-toggle="toggle" data-on="No" data-off="Yes" data-onstyle="default" data-offstyle="success">
</label>
</div>
<div class="form-group">
<label for="green">Green
<input name="green" class="button" type="checkbox" data-toggle="toggle" data-on="No" data-off="Yes" data-onstyle="default" data-offstyle="success">
</label>
</div>


I was also looking to use a script like this one

<script type="text/javascript">
$(document).ready(function () {
$('.selecctall').click(function (event) {
if (this.checked) {
$('.checkbox1').each(function () {
this.checked = true;
});
} else {
$('.checkbox1').each(function () {
this.checked = false;
});
}
});

});



Answer

I think I've got what you're looking for in the fiddle below. I've got it set up so if other colors are added (other than blue and yellow) and we want them to behave like blue and yellow we won't need to make any code changes. The logic is if green is checked => uncheck all others and don't let them be selected. If all others are checked => select green and uncheck all others. More comments are available in the code:

Fiddle w/ solution

var $green = $('.button[name="green"]'), //Get our special input, "green"
    $notGreen = $('.button').not($green); //Get all other inputs

$('.form-group').on('change', '.button', function() { //Attach handler at parent and delegate to .button class
    if (!$(this).is(':checked')) { return; } //Only want to act when something is being checked

    if ($green.is(':checked')) {
        //If green is checked, want to uncheck everything else
        $notGreen.prop('checked', false); //.prop is the best way to uncheck
    }
    else if ($notGreen.filter(':checked').length === $notGreen.length) {
        //If every other input other than green is checked, check green and uncheck everything else
        $notGreen.prop('checked', false);
        $green.prop('checked', true);
    }
});