2015-08-31 117 views
0

当我想使用jquery开发checkall函数时遇到了一些问题。使用jquery检查所有具有特定值的复选框

我把所有的复选框放在表格中,以清除它,并且希望检查所有复选框的值为input

例如,当我单击值为type1的复选框时,将同时检查包括type1在内的所有复选框值(type1,type1-1和type 1-2)。

HTML:

<table> 
    <tr class='type1'> 
     <td><input type="checkbox" value="type1"></td> 
     <td>Type_1<td> 
    </tr> 
    <tr class='type1-1'> 
     <td><input type="checkbox" value="type1-1"></td> 
     <td>Type_1-1<td> 
    </tr> 
    <tr class='type1-2'> 
     <td><input type="checkbox" value="type1-2"></td> 
     <td>Type_1-2<td> 
    </tr> 
    <tr class='type2'> 
     <td><input type="checkbox" value="type2"></td> 
     <td>Type_2<td> 
    </tr> 
    <tr class='type2-1'> 
     <td><input type="checkbox" value="type2-1"></td> 
     <td>Type_2-1<td> 
    </tr>   
</table> 

是否有可能用jQuery做呢?

谢谢。

回答

1

你可以这样说:

$(':checkbox').change(function() { 
    var chkValue=$(this).attr("value"); 
    if($(this).is(':checked')) 
    {  
     $(':checkbox[value*="'+chkValue+'"]').prop('checked', true); 
     //use selector^= OR selector*= as per your need 
    } 
    else 
    { 
     $(':checkbox[value*="'+chkValue+'"]').prop('checked', false); 
    } 
}); 

FIDDLE DEMO