最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - toggle classes between two radio buttons in jquery - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Jan 28, 2012 at 4:44 user765368user765368 20.4k27 gold badges102 silver badges171 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Try this.

$("input[name='sport']").click(function(){
   $("input[name='sport']").removeClass('className');   
   $(this).addClass('className');
});

Demo

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/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.

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.

发布评论

评论列表(0)

  1. 暂无评论