2016-01-22 27 views
0

我有這個jQuery的位,它添加一個.selected類的單選按鈕的標籤,當它被選中。如何獲取每個選定的無線電輸入以保留其邊界?

但我想這對每個組單選按鈕的工作

HTML:

組1

信用卡/借記卡

<div class="radio radio--inline"> 
    <label for="offline"> 
     <input type="radio" name="payment-option" id="offline" value="offline"> Offline Payments 
    </label> 
</div> 

<h1>Group 2</h1> 
<div class="radio radio--inline"> 
    <label for="credit-card1"> 
     <input type="radio" name="payment-option2" id="credit-card1" value="credit-card"> Credit/Debit Card 
    </label> 
</div> 

<div class="radio radio--inline"> 
    <label for="offline1"> 
     <input type="radio" name="payment-option2" id="offline1" value="offline"> Offline Payments 
    </label> 
</div> 

CSS:

.selected { 
    border: 2px solid purple; 
} 

jQuery的:

$(function() { 
var $radioButtons = $('.radio input[type="radio"]'); 
    $radioButtons.click(function() { 
    $('label').removeClass('selected'); 
    $(this).closest('label').addClass('selected'); 
}); 
}); 

參見:http://jsbin.com/biciku/edit?html,css,js,output

回答

0

您要刪除.selected形式的所有label秒。

變化這

$( '標籤')removeClass( '選擇')。

$('.radio input[type="radio"]').not(':checked').parent('label').removeClass('selected'); 

全碼:

$(function() { 
    var $radioButtons = $('.radio input[type="radio"]'); 
    $radioButtons.click(function() { 

    $('.radio input[type="radio"]').not(':checked').parent('label').removeClass('selected'); 
    $(this).closest('label').addClass('selected'); 
    }); 
}); 

檢查:http://jsbin.com/sogejecodi/1/edit?html,css,js,output

0

只是檢查他們都每次:

$radioButtons.click(function() { 
    $("label").each(
    function(){ 
     var $t = $(this); 
     $t[$("#" + $t.prop('for') + ':checked').length > 0 ? 'addClass' : 'removeClass']('selected'); 
    }); 
}); 
0

這將成爲你改變你的HTML匹配的信息結構清潔和更容易。

更新jsbin: http://jsbin.com/ruhamuquyo/1/edit?html,css,js,output

我包裹每個字段集在<fieldset>並提出一些小的改進,如改變點擊監聽來改變,並加入透明邊框圍繞非選擇標籤,以防止在邊界變化的抖動。

相關問題