0

I have a code that checks if radio buttons are checked and if they are it set background color. It's all working fine, my problem is when I want to select another radio button, result is that all my radio buttons are selected on click but it needs to be just one.

$("input[type='radio']").each(function () {
  if ($(this).is(":checked")) {
  $(this).css("background", "yellow");
   }
 });
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio">
<input type="radio" checked>

You can test this out. Just try to select another radio button, you will see that radio buttons are selected (2 radio buttons).

What I want to achieve is that when you click on another radio button it needs to remove this checked class or any other idea. I can't switch between radio buttons.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
jomskris
  • 293
  • 6
  • 17

4 Answers4

0

Give them the same name:

$("input[type='radio']").each(function() {
  if ($(this).is(":checked")) {
    $(this).css("background", "yellow");
  }
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<input type="radio" name="radio">
<input type="radio" name="radio" checked>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0
<input type="radio" name="sameName">
<input type="radio" name="sameName">

set their name like this way

KimDDuShi
  • 58
  • 8
0

Radio button can be easily handle with name attribute below code may help you

<input type="radio" name="color">
<input type="radio"  name="color" checked>

$("input[name='color']").each(function () {
    if ($(this).is(":checked")) {
      $(this).css("background", "yellow");
    }
});
0

To achieve the desired behavior with visible background color for each radio button, you could wrap each radio <input /> with a span element which would achieve the visual effect of a background color for the radio buttons:

/* Reusable selection of radio buttons */
const radioButtons = $("input[type='radio']");

/* Updates selected radio button parent backgrounds based on checked state */
function updateBackground() {
  radioButtons.each(function() {
    $(this).parent().css('background', $(this).is(":checked") ? 'yellow' : '');
  });
}

/* Attach click behavior to each causing the background colors to update */
radioButtons.click(updateBackground);

/* Initalise the backgrounds and */
updateBackground();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!-- Wrap each radio button with a span, which will be used to show a colored background 
when the radio button is checked -->
<span>
  <input type="radio" name="radio-group-name" checked>
</span>
<span>
  <input type="radio" name="radio-group-name">
</span>
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65