tags:

views:

72

answers:

4

So I'm starting to get into jquery more and more lately. I've created custom radio buttons and doing this to show that a radio button is selected:

 $('.radio_1').mousedown(function() {
  $(this).toggleClass('selected');
  $('.radio_2').removeClass('selected');
  $('.radio_3').removeClass('selected');
 });
 $('.radio_2').mousedown(function() {
  $(this).toggleClass('selected');
  $('.radio_1').removeClass('selected');
  $('.radio_3').removeClass('selected');
 });
 $('.radio_3').mousedown(function() {
  $(this).toggleClass('selected');
  $('.radio_2').removeClass('selected');
  $('.radio_1').removeClass('selected');
 });

Using CSS, I've hidden the actual radio button itself. Is there a way of slimming this down a bit to lose the repetitiveness?

Thanks!

A: 

Give the buttons a parent, and select off that. Also, it would be easier if each had just one class, such as .my-radio or something. At the worst, though, you should be able to do this.

 $('.radio_1, .radio_2, .radio_3').mousedown(function() {
   $('.radio_1, .radio_2, .radio_3').removeClass( 'selected' );
   $(this).addClass('selected');
 });
Stefan Kendall
I'm going to go with the one at the top but this did help me with another issue i was having. Thanks!
Marc
+2  A: 

Give all your radio's the same class (.radio in my example).

What the code below is saying is when one of the .radio's is mouse'd down, remove the class .selected from all of the .radio's and add the class .selected to the radio that was clicked.

$('.radio').mousedown(function() {
  $('.radio').removeClass('selected');
  $(this).addClass('selected');
});
Catfish
Wow. That's so much smaller. Thanks a lot!
Marc
Now can I make a child tag appear as well. For example I have a hidden div within the label that I want to appear when this is selected.
Marc
How about this: $('.child').hide(); $('.radio').mousedown(function() { $('.radio').removeClass('selected'); $('.child').slideUp('slow'); $(this).addClass('selected'); $(this).children('.child').slideDown('slow'); });
Marc
+2  A: 
$('[class^=radio_]').mousedown(function() {
  $('[class^=radio_]').removeClass('selected');
  $(this).toggleClass('selected');
});

The 'class^=' gets all the elements that have a class starting with 'radio_'.

Rob van Bentem
This doesn't work given markup containing radio_4, etc.
Stefan Kendall
+2  A: 

You certainly can.

$('.radio').mousedown(function () {
  $(this).toggleClass('selected').siblings('.radio').removeClass('selected');
})
g.d.d.c