Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery add/remove css class on selected radio

Tags:

jquery-ui

I've read a few solutions on here, but my problem differs enough where those will not work. Basically if the radio button is checked, add a css class to the parent div. If the radio is not checked, remove the css class. Sounds simple?

I have more than one radio button group, so in other words, there will be multiple radio buttons selected at a time. Each radio button group also is on different parts of the page seperated by other html.

Here is what I came up with:

  $(document).ready(function () {
    $('input').click(function () {
        if ($('input:not(:checked)')) {
            $('div').removeClass('style1');
        }
        if ($('input').is(':checked')) {
            $(this).parent().addClass('style1');
        }


    });
});

I think I'm on the right path with the input:not(:checked), but on the next line it removes style1 from all div elements instead of checking if other divs radio button child is checked.

I guess what I'm asking is how do I write a script that when a radio button is clicked, add a css class to the parent and then find all div tags on the page that have a child of input. If the divs child input is not checked, remove the css class. So if a div has a child input element and it is checked, don't remove the css class from the inputs div.

I hope that makes sense.

like image 213
The Muffin Man Avatar asked Jul 31 '10 01:07

The Muffin Man


People also ask

Which of the following jQuery method add remove CSS classes from the selected elements?

toggleClass() - Toggles between adding/removing classes from the selected elements.

Which method is used to remove CSS class to the selected elements?

The addClass() method adds a class to the selector and removeClass() removes the CSS class for the selector.

Which jQuery method is used to switch between adding removing CSS classes?

jQuery toggleClass() Method The toggleClass() method toggles between adding and removing one or more class names from the selected elements.

Which method in jQuery is used to add prev and blue class to an element?

The addClass() method adds one or more class names to the selected elements.


1 Answers

Why not using the following: http://jsfiddle.net/Q2bzT/

$(document).ready(function () {
    $('input').click(function () {
        $('input:not(:checked)').parent().removeClass("style1");
        $('input:checked').parent().addClass("style1");
    });    
});​
like image 194
nandokakimoto Avatar answered Oct 05 '22 04:10

nandokakimoto