2017-01-20 39 views
1

我有一些單選按鈕,最初沒有設置css,其中checked =「checked」。如何在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( 「變」)''來。對( )'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

相關問題