2014-09-23 137 views
0

我有很多表格,當一個複選框被選中時 - 所有其他表格都應該清除。您可以檢查此表中任意數量的複選框,但一次只能查看一個表格中的複選框。 我會如何去做這件事?如果可能的話,我想避免使用ID,因爲我有8個表。如果選中表格複選框,取消選中其他表格複選框?

http://jsfiddle.net/69o3e5y4/

$('input[type=checkbox]').on('click', function() { 

}); 
+2

這聽起來像單選按鈕會爲這個完美的。有沒有原因,你不想使用它們呢? – Michael 2014-09-23 17:14:47

+0

@microsby0:「你可以在這張表中檢查任意數量的複選框」 – 2014-09-23 17:15:30

+0

@DarkFalcon啊謝謝,我沒有注意到那部分。你可以使用班級,每個班級一個班級?它比ids好一點 – Michael 2014-09-23 17:16:45

回答

5

您可以:

  1. 得到含表$(this).closest("table")
  2. 然後得到所有其他表:$("table").not($table)
  3. 最後,從這些表中取消所有輸入:... .prop("checked", false)

這應該給一些像這樣的代碼:

$('input[type=checkbox]').on('click', function() { 
    var $table = $(this).closest("table"); // Current table 

    $("table").not($table)     // Other tables 
     .find("input[type=checkbox]:checked") // Checked input of these tables 
     .prop("checked", false);    // Uncheck them 
}); 

看到這個小提琴:http://jsfiddle.net/69o3e5y4/2/

+0

此外,對於每個選中的複選框,我們可以記錄.closest('td')。next()。html()名字?所以如果只有一個被選中,「紅色」,但如果多於一個添加逗號「紅色,藍色」,最後一個詞不應該有逗號「紅色,藍色」。 – triplethreat77 2014-09-23 17:29:47

+0

明白了。 $('input [type = checkbox]')。on('click',function(){ var $ table = $(this).closest(「table」); $(「table」)。not($ ('checkbox':checked')。prop(「checked」,false); var chklist =「」; $('input [type = checkbox]:checked')。each (函數(){ var sThisVal =(this.checked?「1」:「0」); chklist + =(chklist ==「」?sThisVal:「,」+ sThisVal); }); console。 log(chklist); }); – triplethreat77 2014-09-23 17:40:21

-1

我沒有試過,但我會用類。因此,Table1中的所有複選框都將是「Table1」類,Table2中的所有複選框都將放在「Table2」類中,等等。

然後,在事件處理程序中,您可以遍歷頁面上的每個複選框,如果他們的課程與點擊的課程不匹配,則取消選中所有課程。

比如(再次提示,未測試):

 $("input[type=checkbox]").click(function() { 
      if ($(this).prop("checked") == true){ 
       var CurrentClass = $(this).prop("class"); 

       $("input[type=checkbox]").each(function() { 
        if ($(this).prop("class") != CurrentClass) 
         $(this).prop("checked", false); 
       }); 
      } 
     }); 
+0

-1'.prop('class')'?如果複選框有多個類,該怎麼辦? – PeterKA 2014-09-23 17:38:48

+0

prop(「class」)不返回一個列表 - 它返回一個字符串(空格分隔)。如果他的複選框都具有相同的5個類,他可以添加第六個(表名),並且這個代碼將起作用。如果複選框沒有類,他可以添加一個(表名),並且此代碼將工作。 – 2014-09-23 17:48:56

+0

我明白。有太多的變量('如果'),所以這聽起來不是理想的解決方案。 – PeterKA 2014-09-23 18:46:00

0

這個jQuery工作沒有任何標識:

$('table').each(function(index){  
     $(this).find('input').each(function() 
     { 
      $(this).on('click', function() {   
      clearThisTablesCheckboxes(index); 
      }); 

     }); 
}); 

function clearThisTablesCheckboxes(position){ 
    $('table').each(function(index){ 
      $(this).find('input').each(function() 
      { 
       if(position != index) 
       { 
        var prop=false; 
        $(this).prop('checked',prop); 
       } 
      }); 
    }); 

} 

http://jsfiddle.net/csdtesting/69o3e5y4/8/

相關問題