选中时将类添加到广播的标签,如果没有,则删除该类?

时间:2014-02-25 11:49:13

标签: jquery

我的HTML标签内有单选按钮。我需要在选择收音机时为此标签添加一个类,并在不选择时删除该类。

下面的代码在选择收音机时添加了类,但在未选中时不删除它。

http://jsfiddle.net/UJM6G/

<div class="form-input radios"> <div class="form-radios form-element-type-radios"><div class="form-form-element-wrapper"><div class="form-item form-item-radio">
<div class="form-input radio"> <label class="option" for="edit-vehicle-owner-1"><input type="radio" name="vehicle_owner" value="1" class="form-radio form-element-type-radios"> Yes</label>
</div><div class="form-error"></div></div>
</div><div class="form-form-element-wrapper"><div class="form-item form-item-radio">
<div class="form-input radio"> <label class="option" for="edit-vehicle-owner-0"><input type="radio" value="0" class="form-radio form-element-type-radios"> No</label>
</div><div class="form-error"></div></div>
</div></div>
</div>

  $('.form-element-type-radios').click(function(){
    if ( $('input.form-radio').is(':checked') ) {
      $(this).parent('label').addClass('checked');
    }
    else {
      $(this).parent('label').removeClass('checked');
    }
  });

2 个答案:

答案 0 :(得分:3)

您应该使用.change()事件

$('input.form-radio').change(function () {
    if ($(this).prop('checked')) {
        $('input.form-radio').parent('label').removeClass('checked')
        $(this).parent('label').addClass('checked');
    }
}).change();

DEMO

答案 1 :(得分:0)

尝试使用每个功能

为所有按钮执行此操作
$('.form-element-type-radios').click(function(){
    $('input.form-radio').each(function(){
      $(this).is(':checked') ? $(this).parent('label').addClass('checked') : $(this).parent('label').removeClass('checked');
        })
  });

JSFIDDLE DEMO

相关问题