Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Ajax checkbox state

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?

like image 913
oshirowanen Avatar asked Jun 25 '10 11:06

oshirowanen


4 Answers

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>
like image 109
oshirowanen Avatar answered Oct 03 '22 18:10

oshirowanen


Combining your solution and the accepted answer by Ain:

<script type="text/javascript">
  $(document).ready(function(){
    var isChecked = $("input:checkbox").is(":checked") ? 1:0; 
    $.ajax({
            url: 'on_off.aspx',
            type: 'POST',
            data: { strID:$("input:checkbox").attr("id"), strState:isChecked }
    });        
  });
</script>
like image 45
chridam Avatar answered Oct 03 '22 17:10

chridam


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

will do the job.

like image 27
Ain Tohvri Avatar answered Oct 03 '22 18:10

Ain Tohvri


Adding back in the change event to the merged solution. Want this to fire every time checkbox is changed.

<script type="text/javascript">
    $(document).ready(function(){
        $("input:checkbox").change(function() { 
            var isChecked = $("input:checkbox").is(":checked") ? 1:0; 
            $.ajax({
                url: 'on_off.aspx',
                type: 'POST',
                data: { strID:$("input:checkbox").attr("id"), strState:isChecked }
            });        
        });        
    });
</script>
like image 39
stuart Avatar answered Oct 03 '22 19:10

stuart