Search code examples
javascriptcustom-selectors

javascript add class to a class based on radio select


i'm not that well versed with javascript so i'm looking for some help. I am looking for a way to apply a class to the main class of the following block via javascript in opencart

<div class="mainclass">

    <div class="childclass">
    ....
    <input type="radio" ..../>

    <?php } else { ?>
   ....

using the following code of javascript works but works only on the childclass and i want it to apply to mainclass. i can see that the code basically say to apply to the parent of the input so its correct. but how do i extend or climb up so that in applies to the mainclass?

$(document).ready(function () {
$('input').click(function () {
$('input:not(:checked)').parent().removeClass("checked");
$('input:checked').parent().addClass("checked");
});
$('input:checked').parent().addClass("checked");
});

Solution

  • Change parent() to parents() and add .mainclass to parents(). You then search for a parent with class = mainclass and apply the class checked to that div.

    $(document).ready(function () {
        $('input').click(function () {
            $('input:not(:checked)').parents('.mainclass').removeClass("checked");
            $('input:checked').parents('.mainclass').addClass("checked");
        });
        $('input:checked').parents('.mainclass').addClass("checked");
    });
    

    See http://jsfiddle.net/fam04sro/1/