2014-10-04 40 views
0

我有複選框,其行爲與單選按鈕相似,因此只能在一組複選框中選中一個複選框。它們按輸入類分組。jQuery只能檢查一個複選框,但也可以取消選擇它

但我也想有可能取消選中複選框,現在正在我的代碼中被阻止。

如何使用此功能使所有複選框「不可選」?謝謝。

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<input type="checkbox" name="fruit" value="fruit" class="classname">I like fruits 
<br> 
<input type="checkbox" name="vegetable" value="vegetable" class="classname">I like vegetables 

的JavaScript:

$(document).ready(function() { 
    var $unique = $('input.classname'); 
    $unique.click(function() { 
     $unique.removeAttr('checked'); 
     $(this).attr('checked', true); 
    }); 
}); 

JSFiddle example over here

回答

3

你可以嘗試處理只喜歡選擇操作

$(document).ready(function() { 

    var $unique = $('input.classname'); 
    $unique.change(function() { 
     if (this.checked) { 
      $unique.not(this).prop('checked', false); 
     } 
    }); 

}); 

演示:Fiddle

相關問題