views:

370

answers:

4

I'm trying to add a class to the selected radio input and then remove that class when another radio of the same type is selected

The radio buttons have the class 'radio_button' but i can't get the class to change with the below code.

  jQuery(".radio_button").livequery('click',function() {  

      $('input.radio_button :radio').focus(updateSelectedStyle);
      $('input.radio_button :radio').blur(updateSelectedStyle);
      $('input.radio_button :radio').change(updateSelectedStyle);
  }
  function updateSelectedStyle() {
      $('input.radio_button :radio').removeClass('focused');
      $('input.radio_button :radio:checked').addClass('focused');
  }
+1  A: 
  • Give each radio button a unique ID
  • Pass the ID on the click
  • Remove the "focussed" class name for all the radio buttons with the same class
  • Add the "focussed" class to the radio button with the ID you passed
Diodeus
+2  A: 

Tre problem is caused by one extra space in your selectors.

Instead of:

$('input.radio_button :radio')

you wanted to write:

$('input.radio_button:radio')
Rene Saarsoo
A: 

First, I agree with Rene Saarsoo's answer about the extra space.

Second, are you also trying to apply the style to the radio button label? You probably want to wrap the buttons and labels together somehow. For example:

<span class="radiowrapper"><input type="radio" name="system" value="1" class="radio_button"> 1</span>
<br>
<span class="radiowrapper"><input type="radio" name="system" value="2" class="radio_button"> 2</span>

Then get rid of the extra calls in your livequery call and move the code from updateSelectedStyle() function into your livequery call (I noticed issues with IE otherwise):

   jQuery(".radio_button").livequery('click',function() {
     $('input.radio_button:radio').parent(".radiowrapper").removeClass('focused');
     $('input.radio_button:radio:checked').parent(".radiowrapper").addClass('focused');
   });
Ben Koehler
+2  A: 

You might also want to take advantage of jQuery's chainability to reduce the amount of work you're doing. (Rather than re-finding these buttons over and over again.) Something like this:

  jQuery(".radio_button").livequery('click',function() {  
    $('input.radio_button:radio')
      .focus(updateSelectedStyle)
      .blur(updateSelectedStyle)
      .change(updateSelectedStyle);
  });
  function updateSelectedStyle() {
    $('input.radio_button:radio')
      .removeClass('focused')
      .filter(':checked').addClass('focused');
  }
Sixten Otto