Parity Bit Parity Bit - 4 months ago 4
HTML Question

jquery: Changing input label's color

<label>
<input type="radio" id="other" name="level_0" value="other" class="other">other
</label>


Say I have the above in an unordered list. On clicking the radio button, I want the label to be colored red.

I have tried the following:

$('input[type=radio]').click(function(){
if($(this).is(':checked')){
$(this).prev().css("color","red");
}
});


Shouldn't this grab the previous element, 'label', and change its color to red?

Answer

$('input[type=radio]').click(function() {
  if ($(this).is(':checked')) {
    $(this).closest('label').addClass("red");
  }
});
.red {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="radio" id="other" name="level_0" value="other" class="other">other
</label>

  1. Use .closest()
  2. .prev() is used for siblings element.
  3. Can also use .parent()
  4. Suggestion use .addClass() instead of adding style directly