2014-09-23 136 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/

相关问题