2017-01-20 9 views
1

私はいくつかのラジオボタンを持っています。jqueryの入力属性に基づいてクラスを追加する方法は?

入力された入力ラジオボタンにクラスを適用するために使用できるjqueryステートメントのタイプは何ですか?

私も付属している私のjsfiddle

https://jsfiddle.net/2Lbbf1b4/1/

$(function() { 
    $('label.radio-inline input').on('change', function() { 
    var name = $(this).attr('name'); 
    if (true === $(this).prop('checked')) { 
     $('[name=' + $(this).attr('name') + ']').parent().removeClass('radio-select'); 
     $(this).parent().addClass('radio-select'); 
    } 
    }); 
}); 


<label class="radio-inline radio-style"> 
    <input type="radio" checked="checked" name="test1" value="1" class="radio-style"> 
</label> 
<label class="radio-inline radio-style"> 
    <input type="radio" name="test1" value="2"> 
</label> 
<br> 
<label class="radio-inline radio-style"> 
    <input type="radio" checked="checked" name="test" value="1" class="radio-style"> 
</label> 
<label class="radio-inline radio-style"> 
    <input type="radio" name="test" value="2"> 
</label> 
+0

チェーン' .change() 'や' .trigger( "変更") ':

$('label.radio-inline input[type=radio]:checked').parent().addClass('radio-select'); 

フィドルをチェック) 'https://jsfiddle.net/2Lbbf1b4/3/ – guest271314

答えて

1

あなたはこのビット簡素化し、それは兄弟だに対してそれを入力のチェック状態を確認し、比較するためのjQueryの.is()ヘルパーメソッドを使用することができます

$(function() { 
    $('label.radio-inline input').on('change', function() { 
     if ($(this).is(':checked')) { 
      $('input[name="' + $(this).prop('name') +'"]').not($(this)).parent().removeClass('radio-select'); 
      $(this).parent().addClass('radio-select'); 
     } 
    }); 
}); 

Updated jsFiddle

:同じ名前を持ちますあなたが使用して初期化時にクラスを設定する必要が
関連する問題