Reputation: 20346
I know this sounds like an easy question but for some reason I just can't figure it out right now. My question is this, let's say I have two radio buttons on my page:
<input type="radio" checked="checked" name=sport value="soccer" />
<input type="radio" name=sport value="basketball" />
What I want to do is that if I click on a radio button, I want to add a class name to it, and if I click on the other radio button, I want to add the same class to that new clicked radio button and I want the class that I added to the previous one removed, and so on....
Any idea please?
Upvotes: 0
Views: 6273
Reputation: 61
This is how I did mine to apply to any radio options so I don't have to specify a name each time. I'm sort of new to this so I'm sure someone will have something to say about it. The parent is a label that I have css as a button
$(".noradio").on('click', function(){
var n=$(this).attr("name");
$("input[name='"+n+"']").parent().removeClass('active').removeAttr('checked'); ;
$(this).parent().addClass('active').attr('checked', 'checked');
});
Oh and .noradio is a class on the input itself.
Upvotes: 1
Reputation: 150040
Well, something like this could do it:
$('input:radio[name="sport"]').click(function() {
$(this).addClass("yourclasshere")
.siblings('input:radio[name="sport"]').removeClass("yourclasshere");
});
Demo: http://jsfiddle.net/yH6ur/
If the radio buttons in your real project are not actually siblings (because they're wrapped in label elements or something) then do it as per Shankar Sangoli's answer.
Upvotes: 3
Reputation: 69915
Try this.
$("input[name='sport']").click(function(){
$("input[name='sport']").removeClass('className');
$(this).addClass('className');
});
Upvotes: 6