developer
developer

Reputation: 658

Checkbox dependencies in jquery

I'm trying to implement dependencies between various checkboxes, however, I've a simple scenario that if and checkbox is unchecked, other checkboxes should also be unchecked in ascending order. Let the first checkbox has id=1, and I've total 5 checkboxes, if the first checkbox is unchecked, other check boxes that have id's greater than the current should also be unchecked, i.e. id=2, id=3, id=4, id=5 should also be unchecked and so on.

My Code:

<input type="checkbox" id="1" class="cb">
<input type="checkbox" id="2" class="cb">
<input type="checkbox" id="3" class="cb">
<input type="checkbox" id="4" class="cb">
<input type="checkbox" id="5" class="cb">

$('input.CB').on('change', function() {
    $('input.CB').not(this).prop('checked', false);  
});

Upvotes: 0

Views: 741

Answers (1)

Bl00dsoul
Bl00dsoul

Reputation: 56

If i understood your question correctly you're looking for something like this:

lowest_unchecked = false;
$('.cb').on('change', function(){
    $('.cb').each(function(){

        if( !$(this).prop( 'checked' ) ){
            lowest_unchecked = $(this).attr('id');
        }
        if( lowest_unchecked !== false && lowest_unchecked < $(this).attr('id') ){
            $(this).prop('checked', false);
        }
    });
});

it could be made more efficient by not making it check id's smaller then the one that a change occurs at, but this will probably do just fine for your needs.

Edit: added fiddle on request: https://jsfiddle.net/93o1kkjn/1/

Upvotes: 2

Related Questions