I have a table with 'nested' inputs that need to be checked or unchecked when a button 'select all' is pressed. There are several levels that can be toggled with their respective 'select all' button. In my code I have a repetitive .each()
statement where the second one tests if there are differing numbers of checked/unchecked inputs and if there are it overwrites what the first .each()
statement did. How can I write the following code better?
$(document).ready(function(){
$(".checkAll").click(function(e){
e.preventDefault();
var thisRow = $(this).parents("tr");
var thisRowNumber = parseInt(thisRow.attr("id").replace("row",""));
var thisLevel = parseInt(thisRow.children().first().attr("class").replace("textlevel",""));
var checked = 0;
var unchecked = 0;
$(".tablefull tr").each(function(){
if($(this).attr("class") !== "heading"){
r = parseInt($(this).attr("id").replace("row",""));
if(r > thisRowNumber){
n = parseInt($(this).children().first().attr("class").replace("textlevel",""));
if(n === thisLevel){
return false;
}
if(n > thisLevel){
$(this).find("input[name='ci_id']").prop("checked",function(index, oldAttr){
if(oldAttr){
checked++;
}
else {
unchecked++;
}
return !oldAttr;
});
}
}
}
});
if(checked > 0 && unchecked > 0){
$(".tablefull tr").each(function(){
if($(this).attr("class") !== "heading"){
r = parseInt($(this).attr("id").replace("row",""));
if(r > thisRowNumber){
n = parseInt($(this).children().first().attr("class").replace("textlevel",""));
if(n === thisLevel){
return false;
}
if(n > thisLevel){
$(this).find("input[name='ci_id']").prop("checked",true);
}
}
}
});
}
});
});
here's the working code in a fiddle: http://jsfiddle.net/KnU4X/1/
here's the code without my lengthy fix in a fiddle: http://jsfiddle.net/KnU4X/2/
To see the problem, click 'select all' with level 1, then 'select all' with level 2, then 'select all' with level 1 again. You will notice it unchecks everything except the level 2 which becomes checked.
Is there a way to remove all that seemingly redundant code and keep that functionality?