views:

63

answers:

3

I have checkboxes on my page for which I would like to send their state back to the database via ajax. I know how to use jquery with ajax, but I don't know how to get the checked state, both checked and unchecked along with the id of the checkbox so I can send it back to the server.

Any ideas?

A: 

Well it's easy enough to find the checkboxes:

$(':checkbox').whatever()

The trick is that in HTML checkboxes only have a value that's meaningful when checked. When they're not checked, what do you tell the server?

Well if you've got a convention to work with (perhaps always sending "true" when checked and "false" when not checked), the next thing you have to decide is how to get them to your server. You can use the jQuery param function to turn the list into a parameter string:

var params = $.param($(':checkbox').map(function() {
   return { name: this.id, value: !!this.checked };
}));

That gives you a string ready to be tacked onto a URL, or sent as data via $.ajax.

Pointy
+3  A: 
if ($("#yourCheckboxID").is(":checked")) {  
    // checkbox is checked 
} else {
    // checkbox is not checked 
}

will do the job.

Ain
Works nicely! Thanks.
oshirowanen
A: 

Something like this:

<script type="text/javascript">
    $(document).ready(function(){
        $("input:checkbox").change(function() { 
            if($(this).is(":checked")) { 
                $.ajax({
                    url: 'on_off.aspx',
                    type: 'POST',
                    data: { strID:$(this).attr("id"), strState:"1" }
                });
            } else {
                $.ajax({
                    url: 'on_off.aspx',
                    type: 'POST',
                    data: { strID:$(this).attr("id"), strState:"0" }
                });
            }
        }); 
    });
</script>
oshirowanen