Toggle non-consecutive checkboxes with jQuery UI
Posted on:Tuesday, December 27th, 2011 by Ashish DattaYou’re all probably familiar with the UI convention of allowing users to select ALL or NONE for a list of checkboxes (like in Gmail). Recently I was working on a project that had a large table full of checkboxes (imagine a 10×10 grid) where the user would need to toggle some but not all of the checkboxes in a given row. And to make matters more complex, they would need to toggle groups of non-consecutive checkboxes (say 15, skip 10, 5, etc.). I threw on the thinking cap but couldn’t think of any similar interactions I’d seen and couldn’t think of a particularly good way to achieve this.
Enter jQuery UI. I happened to stumble across the jQuery UI Selectable documentation and realized it would provide a good UI experience to toggle some but not all of the checkboxes. The code to implement this is surprisingly simple:
Note: You don’t actually need the div container – that was just for JSFiddle.
<div id="checkboxes">
<table id="checkboxTable">
<tr>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
</table>
</div>
And then the Javascript (jQuery + jQuery UI):
$("#checkboxes").selectable( {filter: "input:checkbox",
stop: function(event, ui) {
$(".ui-selected").each( function(){
$(this).each( function(){
var val = $(this).attr("checked") ? null : "checked";
$(this).attr("checked", val);
});
});
}});
You can check out a live demo at http://jsfiddle.net/whMyQ/3/
As always, questions and comments are welcome!

"
+ "