2010-09-07 75 views
4

我有一個複選框列表分組。 其中一些複選框可能出現在多個部分中。 我想要做的是停止用戶在多個部分中選擇相同的複選框,方法是禁用所有用戶選擇複選框時相同的複選框。 但是他們選中該複選框不能被禁用,因此他們可以取消它(這還必須重新啓用所有禁用的複選框,以便他們可以自由在其他部分,以選擇它,如果他們願意的話)JQuery - 選中時禁用重複複選框

有誰知道最好的方法在JQuery中做到這一點?

示例代碼:

<h3>Section 1</h3> 
<ul> 
    <li> 
     <label for="section1_method_1"> 
      <input name="method_1" value="43" id="section1_method_1" type="checkbox">Option 1 
     </label> 
    </li> 
    <li> 
     <label for="section1_method_2"> 
      <input name="method_2" value="2" id="section1_method_2" type="checkbox">Option 2 
     </label> 
    </li> 
    <li> 
     <label for="section1_method_5"> 
      <input name="method_5" value="6" id="section1_method_5" type="checkbox">Option 5 
     </label> 
    </li> 
</ul> 

<h3>Section 2</h3> 
<ul> 
    <li> 
     <label for="section2_method_0"> 
      <input name="method_0" value="5" id="section2_method_0" type="checkbox">Option 0 
     </label> 
    </li> 
    <li> 
     <label for="section2_method_1"> 
      <input name="method_1" value="143" id="section2_method_1" type="checkbox">Option 1 
     </label> 
    </li> 
</ul> 

,你可以看到選項1只同時出現在第1節和2他們每個人都有不同的id,但名稱是一樣的。

我寧願通過複選框來做,因爲用戶可能沒有意識到他們已經在不同的部分選擇了相同的選項,而如果複選框被禁用,他們會知道他們已經選擇了它,如果他們想改變他們的選擇,他們將不得不實際取消選中它。

+1

我想知道,如果你的表單需要複選框。那麼radiobuttons呢?給出一個代碼示例,也許是表單的截圖。 – Stefanvds 2010-09-07 10:08:51

回答

6

我不會禁用複選框,我只想結合在一起,讓他們改變這一切是這樣的:

$('input[type=checkbox]').change(function(){ 
    name = $(this).attr('name'); 
    checked = $(this).attr('checked'); 
    // this will set all the checkboxes with the same name to the same status 
    $('input[type=checkbox][name='+name+']').attr('checked',checked); 
});​ 

working example


更新:要禁用其他複選框:

$('input[type=checkbox]').change(function(){ 
    name = $(this).attr('name'); 
    id = $(this).attr('id'); 
    checked = $(this).attr('checked'); 
    // disable all checkboxes except itself 
    $('input[type=checkbox][name='+name+']:not(#'+id+')') 
     .attr('disabled',checked); 
});​ 

working example


更新2:爲灰色不可用相應的標籤太:

$('input[type=checkbox]').change(function(){ 
    name = $(this).attr('name'); 
    id = $(this).attr('id'); 
    checked = $(this).attr('checked'); 
    $('input[type=checkbox][name='+name+']:not(#'+id+')') 
     .attr('disabled',checked) 
     .each(function(){ 
      lid = $(this).attr('id'); // the id of the current disabled box 
      if (checked) { 
       $('label[for='+lid+']').addClass('disabled'); 
      } else { 
       $('label[for='+lid+']').removeClass('disabled'); 
      } 
     }); 
});​ 

和一些CSS:

.disabled { 
    color: #888; 
} 

working example

+0

我想禁用它們,而不是像提交表單時那樣綁定它們我想獲取它們實際選擇的值(雖然它們具有相同的名稱,但根據它們被選中的部分,它們具有不同的值)。 – John 2010-09-07 10:28:23

+0

然後我會使用jigfox的解決方案,並將其更改爲取消全部選中,然後檢查當前的一個。 – 2010-09-07 10:37:09

+0

我已經更新了我的回答 – jigfox 2010-09-07 10:39:32