<input type="checkbox" class="christmasCheckBox" name="additionalDonationCheckbox" value="yes" id="additionalDonationCheckbox"
<?php echo (isset($_POST['additionalDonationCheckbox'])&&($_POST['additionalDonationCheckbox']!='')) ? 'checked="checked"' : ''; ?> />
$('#additionalDonationCheckbox').click(
function()
{
($(this).attr('checked')) ? alert('checked') : alert('unchecked');
}
);
I have a form, and before I submit it, if i click the checkbox it alerts ‘checked’ if checked and ‘unchecked’ if unchecked.
If i submit the form with the checkbox unchecked, (and something else in the form fails my php validation), and then click the checkbox, the above still works correctly.
However, if i submit the form with the checkbox CHECKED, (and something else in the form fails my php validation) and then click the checkbox, whether it is unchecked or checked it just alerts ‘checked’.
I am guessing this is because i have set the php code in the input to echo ‘checked=”checked”‘, but i cant figure a way around this?
You want to change the way you determine if the element is
checked:Or
This is because
checkedis both a DOM property and a DOM attribute. The difference between them can be important in some situations (like this).The DOM attribute
checkedrefers to the initial state of the checkbox. So if the checkbox was created withchecked="checked", the DOM attributecheckedwill always return'checked', even if the checkbox has since been unchecked.The DOM property
checkedrefers to the current state of the checkbox, and behaves like you want it to. It will return whether a checkbox is checked now regardless of whether it was checked when the document was loaded.It’s a subtle difference confused by the fact that jQuery is inconsistent on whether
$.attr('checked')returns the attribute or property across versions. Details can be found in the documentation.This is further confused by a bug in jquery 1.6.3 and 1.6.4 that returns a stale value for
$(checkbox).attr('checked')after$(checkbox).click().In summary, if you want to be sure you are getting the current state of the checkbox, either use the
is(':checked')call or theprop('checked')call.