2013-09-25 41 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); 
}); 
相关问题