选中单选按钮更改样式

时间:2009-08-28 15:08:11

标签: javascript jquery

我有一组单选按钮。

<ul class="ProductOptionList">
<li>
<label>
<input class="RadioButton" type="radio" value="157" name="variation[1]"/>
Lemon (200 ml)
</label>
</li>
<li>
<label>
<input class="RadioButton chosen" type="radio" value="160" name="variation[1]"/>
Lemon and Herbs (200 ml)
</label>
</li>
</ul>

我想突出显示所选的那个。

我使用了这段代码:

$('input.RadioButton').click(function() {
    var chkbox = $(this);
      chkbox.is(':checked') ?
        chkbox.addClass('chosen') : $chkbox.removeClass('chosen');

但是如果一个人点击一个变体它会工作并应用该类,那么如果他们点击一秒,它会将该类应用于第二个,但不会从第一个类中删除该类。我如何删除课程? 谢谢!

2 个答案:

答案 0 :(得分:4)

因为您只在点击的电台上激活该功能。试试这个:

$("input.RadioButton").click(function(){
   $("input.RadioButton").removeClass('chosen');
   $(this).addClass('chosen');
})

通过这种方式,您可以从所有无线电中删除“已选择”类,然后仅在单击的类上分配该类。

答案 1 :(得分:0)

首先,您不需要将“RadioButton”作为一个类,因为您可以通过这样的属性选择它们......

$("input[type=radio]")

其次,在将所选类应用于this ...

之前,应将其删除
$("input[type=radio]").click(function() {
  // Remove the class from all inputs that have it
  $("input[type=radio].chosen").removeClass("chosen");

  // Add it to current
  $(this).addClass("chosen");
});