Chris
Chris

Reputation: 17

jQuery radio button checked, else statement not working

I want an input to change its styles (add background color) when checked. This is working, however, the else statement to remove the background color when the input radio type isn't checked is not working.

Have tried various different ways but cannot get the else statement to fire when you click a different input.

HTML:

<tr style="color:white;">
<td id="test" style="background-color:rgb(153, 117, 82);" value="1">
<label><input type="radio" name="c0" class="c0" value="10" onclick="output();" id="t"/>1</label>
</td>
</tr>

<tr style="color:white;">
<td style="background-color: rgb(255, 57, 57);">
<label><input type="radio" name="c0" class="c0" value="20" onclick="output();" id="t"/>2</label>
</td>

JS:

$('input#t').on("click", function() {
if ($("input#t").is(':checked')) {
    $(this).parent().addClass("active");
} 
    else {
    $(this).parent().removeClass("active");
}
});

codepen: https://codepen.io/Not_A_Fax_Machine/pen/zzRMNZ/

Upvotes: 1

Views: 604

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337610

The problem is because you have two elements with the same id attribute - they must be unique.

To fix the problem use a class to group the radio buttons, then use the this keyword to reference the element within the change event handler. Try this:

$('.t').on("change", function() {
  $('label').removeClass('active');
  $(this).parent().toggleClass('active', this.checked);
  // output();
});
tr {
  color: white;
}

td.foo {
  background-color: rgb(153, 117, 82);
}

td.bar {
  background-color: rgb(255, 57, 57);
}

.active {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="foo">
      <label><input type="radio" name="c0" class="t c0" value="10" />1</label>
    </td>
  </tr>
  <tr>
    <td class="bar">
      <label><input type="radio" name="c0" class="t c0" value="20" />2</label>
    </td>
  </tr>
</table>

Note the removal of the inline styles, which should be avoided.

Upvotes: 0

Related Questions