Peter Boomsma
Peter Boomsma

Reputation: 9844

jQuery If checkbox is checked change class

I have two checkboxes called "open_sub_ja" and "open_sub_nee". Only one of them can be checked. Now the thing I'm trying to do is that when the checkbox with the class "open_sub_nee" is checked I want a different div to add a class and when the checkbox "open_sub_nee" looses the checked state I want the other div to remove that class (so a toggle).

I've googled and found something that comes really close to what I want to do (after a b it of modification). This code does add the class "selected" to the right div when the "open_sub_nee" is checked but it does not toggle when the checkbox does not have the checked state.

$('.open_sub_nee').change(function() {
        if($(this).is(':checked')) 
            $(this).parents('.container_vragen').find('.akkoord').addClass('selected'); 
        else
            $(this).parents('.container_vragen').find('.akkoord').removeClass('selected');
    });

I've got a jsFiddle of the project here: http://jsfiddle.net/R5cWW/ allthough the project is getting a bit bigger and my coding isn't the best.

Upvotes: 0

Views: 2434

Answers (1)

Kafoso
Kafoso

Reputation: 554

Why could use a radio button instead?

I'm not entirely sure I understand your question. You want to add a class to the unchecked checkbox's parent div-tag, correct?

$('.open_sub_nee').change(function() {
    if($(this).is(':checked')) {
        $('.open_sub_ja').attr('checked', '').closest('div').addClass('someclass');
    } else {
        $('.open_sub_ja').closest('div').removeClass('someclass');
    }
});

Then do the same for ".open_sub_ja".

Upvotes: 2

Related Questions