Home > other >  How can I add class on main div if I checked the checkbox
How can I add class on main div if I checked the checkbox

Time:10-14

When I checked the checkbox it should add class to the main div. Also when I tried to check again the 2nd checkbox it should be removed on the 1st I checked and add it on the checkbox I checked

Please see code below;

$(".img-rdo :checkbox").change(function() {
  $this.closest(".img-rdo").toggleClass('checked', this.checked);
})

$('.img-rdo .imgRdo').change(function() {
  $(this).closest('.img-rdo').find(':checkbox').prop('checked', this.value != 0).change();
});
.img-rdo {
  background: yellow;
  margin: 10px;
}

.img-rdo.checked {
  background: green;
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="img-rdo" nk-rdo-style="1">
  <input type="radio" id="img-rdo2" name="img-sample-1" class="imgRdo">
  <label class="imgRdo-lbl" for="img-rdo2">
    <div class="rdo-txt">Radio Button with image design component</div>
  </label>
</div>

<div class="img-rdo">
  <input type="radio" id="img-rdo3" name="img-sample-1" class="imgRdo">
  <label class="imgRdo-lbl" for="img-rdo3">
    <div class="rdo-txt">Radio Image</div>
    </label>
</div>

<div class="img-rdo">
  <input type="radio" id="img-rdo4" name="img-sample-1" class="imgRdo">
  <label class="imgRdo-lbl" for="img-rdo4">
    <div class="rdo-txt">Radio Image</div>
  </label>
</div>

CodePudding user response:

You need to change the container class and not wrap a div in a label

$(".imgRdo").change(function() {
  $(".img-rdo").removeClass('checked');
  $(this).closest('.img-rdo').toggleClass('checked', this.checked);
})
.img-rdo {
  background: yellow;
  margin: 10px;
}

.img-rdo.checked {
  background-color: green;
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="img-rdo" nk-rdo-style="1">
  <label class="imgRdo-lbl" for="img-rdo2">
    <input type="radio" id="img-rdo2" name="img-sample-1" class="imgRdo">
    <span class="rdo-txt">Radio Button with image design component</span>
  </label>
</div>

<div class="img-rdo">
  <label class="imgRdo-lbl" for="img-rdo3">
  <input type="radio" id="img-rdo3" name="img-sample-1" class="imgRdo">
    <span class="rdo-txt">Radio Image</span>
    </label>
</div>

<div class="img-rdo">
  <label class="imgRdo-lbl" for="img-rdo4">
  <input type="radio" id="img-rdo4" name="img-sample-1" class="imgRdo">
    <span class="rdo-txt">Radio Image</span>
  </label>
</div>

  • Related