Search code examples
jquerycssradio-buttonlabel

jquery buttonset add class to checked element label


I have run into a problem that I am unsure of how to resolve. According to my debugging using firefox and simple console logs I am doing it correctly. I can see the specified div id for the selected radio button toggle when I select each button. However when using the addClass() funcion the specified class is not getting applied to the selected div id for the checked radio button. Whew what a mouthful.

<script type="text/javascript">
 var $j = jQuery.noConflict();
 $j(document).ready(function(){
  $j('#div :radio').buttonset().click(function(){
   $j(this).find(':checked').attr('id').addClass('');
   $j(this).find(':checked').attr('id').addClass('checked');
  });
 });
</script>

<style>
 .checked{background:url(icon.png) left no-repeat;}
</style>

<div id="div">
 <p><input type="radio" id="radio-1" name="radio" value="radio-1" /><label for="radio-1">Radio-1</label></p>
 <p><input type="radio" id="radio-2" name="radio" value="radio-2" /><label for="radio-2">Radio-2</label></p>
 <p><input type="radio" id="radio-3" name="radio" value="radio-3" /><label for="radio-3">Radio-3</label></p>
</div>

Solution

  • .attr() returns a string, and your code calls .addClass() on that string. It should be obvious that won't work. You don't want to add the class to the ID — in fact you can't, because there is no String.addClass method.

    Try this:

    $j('#div').delegate('input[type="radio"]', 'change', function ()
    {
        $j(this).parent().toggleClass('checked', this.checked);
    });
    

    Edit

    Is this more like what you're looking for? http://jsfiddle.net/mattball/ACREd/