2013-09-25 38 views
0

我有以下幾點:使用jQuery取消所有的複選框,然後選中點擊一個

 <div class="pricing-levels-2"> 
     <p>Which level would you like? (Click all that apply)</p> 
     <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 1<br> 
     <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br> 
     <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br> 
     <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br> 
     <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br> 
     <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br> 
     <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br> 
     </div> 
     <div class="pricing-levels-3"> 
     <p>Which level would you like? (Click all that apply)</p> 
     <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br> 
     <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br> 
     <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br> 
     </div> 

我想.pricing-levels-2複選框每次我在其中的一個單擊清除,所以我所做的:

jQuery('.pricing-levels-2 .single-checkbox').on('click', function(){ 
    jQuery('.pricing-levels-2 .single-checkbox').attr('checked', false); 
    jQuery(this).attr('checked', true); 
}); 

但問題是,現在所有的複選框都清除了,即使是我選擇的複選框。所以我不能選擇任何(我想要點擊我選擇的那個)。

我在做什麼錯了?

回答

5

您需要使用.prop代替:

jQuery('.pricing-levels-2 .single-checkbox').on('click', function(){ 
    jQuery('.pricing-levels-2 .single-checkbox').prop('checked', false); 
    jQuery(this).prop('checked', true); 
}); 
1

通過attr

jQuery('.pricing-levels-2 .single-checkbox').on('click', function(){ 
     jQuery('.pricing-levels-2 .single-checkbox').removeAttr('checked'); 
     jQuery(this).attr('checked', 'checked'); 
    }); 

參考removeAttr

通過prop

jQuery('.pricing-levels-2 .single-checkbox').on('click', function(){ 
    jQuery('.pricing-levels-2 .single-checkbox').prop('checked', false); 
    jQuery(this).prop('checked', true); 
}); 
相關問題