Radio - add class at div when checked

Viewed 64

How to add addition class in JS to the div or table , when radio input is checked ?

I would like add class table-selected , to the div class="table-item" when I checked a radio input .

$(".table-item input").change(function() {
  var div = $(this).closest('.table-item');
  $(this).is(":checked") ? div.addClass("table-selected") : div.removeClass("table-selected");
});
#test .table-item {
  border: solid 1px #666;
  height: 25px;
  background-color: #CCC
}

#test .table-selected {
  border: 1 px solid #F00;
  background-color: #00F
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">

  <div class="table-item">
    <div><label for="check1"><input type='radio' name='rad' value='1'>1</label></div>
  </div>
  <div class="table-item">
    <div><label for="check2"><input type='radio' name='rad' value='2'>2</label></div>
  </div>
  <div class="table-item">
    <div><label for="check3"><input type='radio' name='rad' value='3'>3</label></div>
  </div>

</div>

But this work some wrong , add class , but it does not remove it when unchecked

2 Answers

You are just removing the class from the selected div. The else part of that ternary condition would never be satisfied because there div represents the button that you selected.

You need to remove the class from all the divs.

$(".table-item").removeClass('table-selected');
var div = $(this).closest('.table-item');
if ($(this).is(":checked")) {
  div.addClass("table-selected");
}

Check here: https://jsfiddle.net/g5o2w47v/

You have to remove class from other before adding to current. Triggers fire for only that element, so check will run for that element not others. Update Link: https://jsfiddle.net/m637ndrx/2/

 $(".table-item input").change(function() {
  var div = $(this).closest('.table-item');
  $('.table-item').removeClass("table-selected")
  $(this).is(":checked") ? div.addClass("table-selected") : div.removeClass("table-selected");
});
Related