Joffrey Joffrey - 1 month ago 8
Javascript Question

How to add class in div after clicking the div that has radio button in javascript

Im having problem on how to add a class in a div where it has a radio button. What I want is when I clicked the div, the radio button inside the div will mark checked and also the div container of the radio button will have a background of red.

Here's my javascript code

$( document ).on( 'click', 'div#wrapper-radio', function(event) {
if( $(this).find("input[type='radio']").prop("checked") == false){
if($(this).hasClass('panelLink__item--radio-checked') == false ){
$(this).find("input[type='radio']").prop("checked", true);
$(this).addClass('panelLink__item--radio-checked');
}
}
});


The problem with my code is that, it will work on the first click but when I click on another div that has radio button, the class still remain. Below is the image

out of my code above

Can anyone help me what do I need to add in my code? Or is there another way to get what I want? Please advise

Answer

Remove the class from all the wrappers just before you add it to one:

$( document ).on( 'click', 'div#wrapper-radio', function(event) {
    if( $(this).find("input[type='radio']").prop("checked") == false){
        if($(this).hasClass('panelLink__item--radio-checked') == false ){
            $(this).find("input[type='radio']").prop("checked", true);
            $('div#wrapper-radio').removeClass('panelLink__item--radio-checked');
            $(this).addClass('panelLink__item--radio-checked');
        }
    }
});