I have a bunch of related checkboxes, with integer values. I’m trying to encompass the simple logic that:
- when you tick a box, all the boxes with a value <= should get automatically ticked.
- when you untick a box, all the boxes with a value > should get automatically unticked.
This is what I’ve got, which works, but takes up sixteen lines and looks a bit repetitive. Is there a better way?
$('.chk_level').click(function(event){
var this_val = parseInt( $(this).val() );
var this_is_checked = $(this).is(':checked');
$('.chk_level').each(function(i,chk){
var $chk = $(chk);
if ( this_is_checked ){
if ( parseInt( $chk.val() ) <= this_val ){
$chk.attr('checked', true);
}
}else{
if ( parseInt( $chk.val() ) > this_val ){
$chk.attr('checked', false);
}
}
});
});
Your logic seems odd as if you are unchecking higher values, then you can make all checkboxes unchecked, and then only check the lower ones which are required. With this in mind the following works in the same way as your OP example:
Example fiddle