View Full Version : JQuery: how to pass var for checkboxes?

11-29-2009, 03:29 AM
I have a form which has a checkbox input field

<div><input type="checkbox" id="emailSubscription" name="emailSubscription" value="1" <?php if($userActiveDailyEmail==1){ echo 'checked'; } ?> /> daily email reminder of the new case of the day</div>

If the user checks it or unchecks it (toggles it) I want my jquery ajax function to update the mysql table depending on if the box is checked (value = 1) or not (value = 0)

<script type="text/javascript">
$('#emailSubscription').click(function() {
var emailSubscription = $("#emailSubscription").val();
method: "get",
url: "ajax_emailSubscription.php",
data: "emailSubscription="+emailSubscription
}); //close $.ajax(
}); //close click(
}); //close $(

The problem is that no matter if the checkbox is checked or unchecked the alert always defines the value of emailSubscription as 1.

How do I make it so that if the checkbox is unchecked emailSubscription = 0 and if it is checked then emailSubscription=1 ?

11-29-2009, 04:22 AM
Testing the value is always going to give the value, which you've set to 1. Rather, test for checked (http://docs.jquery.com/Selectors/checked). Here's a snippet from a project I'm working on:

$('div#regions :checkbox').change(function(){
if ($(this).is(':checked'))
// do something
// do something else