ryu's blog just a few lines of code

28Jun/090

HOWTO: Check/Uncheck unknown number of checkboxes with jQuery

My attempt for this short script was building a private messaging frontend in a social community system. I tried to give the user more comfort while deleting messages by selecting all messages in the opened view. Sooner or later I was stuck by checking all checkboxes at once. I'm using jQuery so i comb through the documentation. Finaly after some time reading and googleing i came to this solution:

<script type="text/javascript">
function del_check_all() {
var toCheck = null;
if ($('#ff_check_all:checked').val())
toCheck = true;
else
toCheck = false;

$(":checkbox[name='ff_check[]']").each(
function(i) {
if (toCheck)
$(this).attr("checked",$(this).val());
else
$(this).attr("checked",null);
}
);
}
</script>

The accompanying HTML source:

<input type="checkbox" name="ff_check_all" onclick="del_check_all()" id="ff_check_all" />

<input type="checkbox" name="ff_check[]" value="45" />
<input type="checkbox" name="ff_check[]" value="112" />
<input type="checkbox" name="ff_check[]" value="91" />
<input type="checkbox" name="ff_check[]" value="36" />

This works for an unknown number of checkboxes. I hope this can help somebody else too.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.