How to select multiple checkboxes with the same class but depending on which items have been selected
I have a table with multiple rows, in this table each row has it's checkbox and a text field (this text field contains class XXX, but is different per row, although sometimes two of more share the same class).
Now I want, when a user selects checkbox 1 (textfield has the class "A") and checkbox 5 (textfield has the class "B") and clicks the button "Select group", to select all other checkboxes which have the textfield with class "A" or class "B" in their row.
I was thinking of using $(this).closest
but I don't know how jQuery really works, so could anyone point me out in the right direction?
Thanks in advance.
Edit some html: http://jsfiddle.net/hg4p6/1/
<table>
<tr>
<td>
<input type='checkbox' id='chk1'>
</td>
<td>
<input type='text' value='123' class='A'>
</td>
</tr>
<tr>
<td>
<input type='checkbox' id='chk2'>
</td>
<td>
<input type='text' value='518' class='C'>
</td>
</tr>
<tr>
<td&开发者_C百科gt;
<input type='checkbox' id='chk3'>
</td>
<td>
<input type='text' value='321' class='B'>
</td>
</tr>
<tr>
<td>
<input type='checkbox' id='chk4'>
</td>
<td>
<input type='text' value='567' class='A'>
</td>
</tr>
<tr>
<td>
<input type='checkbox' id='chk5'>
</td>
<td>
<input type='text' value='971' class='B'>
</td>
</tr>
<tr>
<td colspan='2'><input type='button' value='Select same classes' onclick='Funcion'>
</td>
</tr>
</table>
So basically, when you select the first checkbox, it should select the 4th aswell. And if you select the 3rd checkbox, it should select the 5th aswell.
Here you go
Working demo
$(function(){
$("#selectAll").click(function(){
var className, $table = $("table");
$table.find("input:checked")
.each(function(){
className = $(this).closest("tr").find("input:text").attr('class');
$table.find("input[type:text]."+className)
.closest("tr").find("input:checkbox").attr('checked', true);
});
});
});
My solution:
http://jsfiddle.net/hg4p6/24/
$(function() {
$('#clickme').click(function() {
$('input:checked').each(function() {
var c = ($(this).parent().next().children("input:text").attr("class"));
$("input:text").filter("."+c).parent().prev().children("input:checkbox").prop("checked",true);
});
});
});
$(":button").click(function(){
$("input[type='checkbox']").each(function(){
var is = $(this).closest("td").next("td").children("input").is(".B,.A");
if(is)
$(this).prop("checked",true);
});
});
http://jsfiddle.net/hg4p6/16/
精彩评论