March 13, 2010

jQuery, Dealing with Checkboxes

This post will show you how to get checkbox values with jQuery and how to set checkbox values with jQuery.

In my application I wanted to have two checkboxes and when one box was unchecked to check the other checkbox (to always keep one check box checked) But I didn’t want to use radio buttons. I also wanted to tie an ajax call to the checking of a checkbox. Here is how I used jQuery to accentuate the behavior of the checkboxes.

Here is my HTML:

<label for=open>open: </label><input class="switch" name="open" type="checkbox" checked>
<label for=closed>closed: </label><input class="switch" name="closed" type="checkbox" >






Here’s the segment of jQuery used to get and set the checkboxes:

$('input:checkbox').live("change", function() {
        $("#display").html('Loading...<br><br><img src="images/small_wait.gif" style="border:none;">');
        if($(this).attr("checked") === true) {
                //uncheck this checkbox
                $(this).find("checkbox").removeAttr("checked");
        } else {
                //check this checkbox
                $(this).find("checkbox").attr("checked","checked");
                if($('input:checkbox').not($(this)).attr("checked") == false) {
                        $('input:checkbox').not($(this)).attr("checked","checked");
                }
        }
        if($(this).attr("name") == "open") {
                //get status of open and closed checkboxes
                var open = $(this).attr("checked");
                var closed = $(this).next().next().attr("checked");
        } else {
                //get status of open and closed checkboxes
                var closed = $(this).attr("checked");
                var open = $(this).prev().prev().attr("checked");
        }
        //Do AJAX query and response....
        //now do a post of open and closed vars
	var url = "ajaxcallurl.php"
	$.post(url, {open: open, closed: closed}, function(response) {
		//apply response to the display
		$("#display").html(response);
	});
        return false; //don't perform standard checkbox function
});

By returning false you effectively commandeer the change of checkbox and disallow it while replacing it with your more intelligent function. And by using prev() and next() a couple times you can refer to the other checkbox easily. I covered in a question on StackOverflow how to post an array of multiple checkboxes if you are using more of them.

Leave a comment