jQuery addClass if radio button checked

11,311

Solution 1

Try something like

$('input.check').is(':checked').each(function() { 
    $(this).parent().addClass('question-box-active');
});

Solution 2

I think $(this) is not referring to the radiobutton in your case

You could bind the click event of the radio button and decide what to do from there...

$(document).ready(function(){
    $("input.check").click(function(){
        if($(this).is(":checked")){
            $(this).parent().addClass("question-box-active");
        }
    });
});

Solution 3

The this you're using is within the function context of the ready handler callback, so it's not pointing to input.check as you expected.

Try something like this instead:

$(document).ready(function() {

    var foo = $('input.check');

    if ( foo.is(':checked') ) {
        foo.parent().addClass('question-box-active');
    }

});

This is assuming your code logic is correct. I assume, however, that you're trying to do something similar to what Doug provided in another answer. Posting some HTML might help clarify.

Solution 4

This will work.

$(document).ready(function() {

    var foo = $('input.check:checked');

    if ( foo.is(':checked') ) {
        foo.parent().addClass('question-box-active');
    }
});
Share:
11,311
Julesfrog
Author by

Julesfrog

Updated on June 14, 2022

Comments

  • Julesfrog
    Julesfrog almost 2 years

    Can anyone help me with this problem?

    $(document).ready(function() {
        if(
            $("input.check").is(":checked")){
                $(this).parent().addClass("question-box-active");
        }
    });
    

    I'm trying to add a class (question-box-active) to the parent of .check (a radio button) only if it is checked. It works fine if I test with an alert, but I can't manage to add that class.

    Thanks all for the help.

    Update: This is the HTML for the form. I copied only 3 divs out of the 48. As you may have guesses I'm trying to add a class to question-box if the radio button is already checked on page load. So far no luck.

    <div class="question-box">
        <input class="check" type="checkbox" name="question-1" value="1" <?php if(isset($_POST['question-1'])) echo "checked"; ?> />
        <span class="question">1. Save a rainforest or grow organic vegetables</span>
    </div>
    
    <div class="question-box alt">
        <input class="check" type="checkbox" name="question-2" value="1" <?php if(isset($_POST['question-2'])) echo "checked"; ?> />
        <span class="question">2. Solve complicated math problems</span>
    </div>
    
    <div class="question-box">
        <input class="check" type="checkbox" name="question-3" value="1" <?php if(isset($_POST['question-3'])) echo "checked"; ?> />
        <span class="question">3. Act in a movie, play, or television show</span>
    </div>