简体   繁体   中英

Radio buttons group jquery click event

i have 4 radio buttons hidden under each image inside each div.

   <div class="temp-inner" id="someid">
        <?php while($row = mysql_fetch_array($res)){?>
            <div data-id="<?=$row['id'];?>" class="hand  temp-selector">
                <input type="radio" name="templates_id" class="templates_id" value="<?=$row['id'];?>" />
                <label class="temp-type" style="background-image:url(<?=$row['src'];?>)"></label>
            </div>
        <? } ?>
   </div>

i need to make radio button under image = checked, so i decided to create onClick function

$(".hand").on("click", function() {
    $(this).children("input:radio[name=templates_id]").attr('checked',true); 
}

this part works perfect. Now i want to add new class to whole if radio button is checked under it. i thought that i can use if - else statement, but it doesn't work.

$(".hand").on("click", function() {
    $(this).children("input:radio[name=templates_id]").attr('checked',true); 

    if($("input:radio[name=templates_id]").is(":checked")) {
        $(".hand").addClass("active");
    } else {
        $(".hand").removeClass("active");
    } 
};

How can i write it correctly? Thx a lot, best regards!

you can use length property, try:

$(".hand").on("click", function() {
    $(this).children("input:radio[name=templates_id]").attr('checked',true); 

    if($("input:radio[name=templates_id]").length > 0) {
        $(".hand").addClass("active");
    } else {
        $(".hand").removeClass("active");
    } 
};

The following code will check the radio on the div clicked, remove the active class on every div with hand class and add the active class to the div clicked.

$(document).on('click', '.hand', function () {
    $(this).children("input:radio[name=templates_id]").prop('checked', true);
    $(".hand").removeClass("active");
    $(this).closest("div.hand").addClass("active");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM