Reputation: 2584
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!
Upvotes: 1
Views: 176
Reputation: 47988
You certainly can.
$('.radio').mousedown(function () {
$(this).toggleClass('selected').siblings('.radio').removeClass('selected');
})
Upvotes: 2
Reputation: 94
$('[class^=radio_]').mousedown(function() {
$('[class^=radio_]').removeClass('selected');
$(this).toggleClass('selected');
});
The 'class^=' gets all the elements that have a class starting with 'radio_'.
Upvotes: 2
Reputation: 19294
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');
});
Upvotes: 2
Reputation: 67822
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');
});
Upvotes: 0