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?
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>
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>
if ($("#yourCheckboxID").is(":checked")) {
// checkbox is checked
} else {
// checkbox is not checked
}
will do the job.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With