callum.bennett
callum.bennett

Reputation: 686

jquery php form validation checkbox

    <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?

Upvotes: 0

Views: 1188

Answers (1)

mmcnickle
mmcnickle

Reputation: 1607

You want to change the way you determine if the element is checked:

$('#additionalDonationCheckbox').click(
    function()
    {
        $(this).is(':checked') ? alert('checked') : alert('unchecked');
    }
);

Or

$('#additionalDonationCheckbox').click(
    function()
    {
        $(this).prop('checked') ? alert('checked') : alert('unchecked');
    }
);

This is because checked is both a DOM property and a DOM attribute. The difference between them can be important in some situations (like this).

The DOM attribute checked refers to the initial state of the checkbox. So if the checkbox was created with checked="checked", the DOM attribute checked will always return 'checked', even if the checkbox has since been unchecked.

The DOM property checked refers 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 the prop('checked') call.

Upvotes: 1

Related Questions