Wednesday 7 September 2016

JQuery to check a Checkbox is filled out and then add a class to the parent Div.

I had a bit of a struggle with this simple bit of code. And that was because examples I'd found hadn't include the use of .each !!

Here's a couple of searches I'd made - 'javascript checkbox value checked then add class to parent' , 'jquery onload' and 'jquery check an object with no action'

The code that worked for me is as such

 

$("input[type=checkbox], input[type=radio]").each(function(){
                    console.log('loading checkbox object');
                    // is(':checked')
                    if($(this).is(':checked')){
                        $(this).parent().addClass("chked");
                        $(this).parent().parent().addClass("chked");
                    }
                });

No comments: