musings

February 14, 2008

toggle multiple checkboxes with jQuery 1.2.2

Filed under: jQuery — aliaspooryorik @ 10:00 am
Tags:

The problem I had was that I wanted to toggle multiple checkboxes on and off on a form. I’ve done this many times before but can never quite remember how I do it. This is my solution for future reference:

<script type="text/javascript">
<!-- <![CDATA[
$(function(){
	$selectAllLink = $('<p>select all rooms<\/p>')
		.click(function(){
			$roomCheckboxes = $('input[name^="room_id_"]‘);
			if ($roomCheckboxes.size()!=$roomCheckboxes.filter(’:checked’).size()) {
				$(’input[name^="room_id_"]‘).attr(’checked’,'checked’);
				$(this).text(’deselect all rooms’);
			}
			else {
				$(’input[name^="room_id_"]‘).removeAttr(’checked’);
				$(this).text(’select all rooms’);
			}
		})
		.css({cursor:’pointer’, textDecoration:’underline’});

	$(’#room-status-list’).before($selectAllLink);
});
// ]] –>
</script>

The line

$('input[name^="room_id_"]‘)

makes sure that only checkboxes named room_id_1, room_id_2, room_id_3, room_id_4 etc are affected, in case you have other checkboxes that do different things.

The line

$('#room-status-list').before($selectAllLink);

makes sure that this feature is only available to users who have javascript enabled. There is nothing more annoying for users than having links that do nothing!

Hope this helps someone.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.