Search code examples
javascriptjqueryradio-buttonlabel

if an input radio is checked change the parent's color: can't make it work with jQuery


When I click an input radio, <label>'s text should change it's text color.

However it doesn't do the trick with my jQuery code:

$("#radios").find("input").change(function(){
if ($(this).checked)
    $(this).parent().addClass('libelulas');
else
    $(this).parent().removeClass('libelulas');
});

I've been checking with the inspector in chrome and seems like it doesn't even create the class wherever is the parent (label) or the input.

Here's my jsfiddle http://jsfiddle.net/Arkl1te/2MnEU/4/


Solution

  • You needed to wrap it in $(document).ready and use a correct selector on the change() event:

    $(document).ready(function(){
      $(".radios input[type=radio]").change(function(){
          $(this).parent().addClass('libelulas');
      });
    });
    

    jsFiddle here.


    Update:

    Forgot to give example in relation to your code in the question and not just the jsFiddle:

    $(document).ready(function(){ 
      $(".radios input[type=radio]").change(function(){
          $(this).parent().addClass('libelulas');
          $("input[type=radio]:not(:checked)").parent().removeClass('libelulas');
      }); 
    });
    

    jsFiddle here.