I have come across a rather strange behaviour. I have two pages (lets call them page A and page B), both pages contain the following javascript code:
<script type="text/javascript">
$(document).ready(function(){
$('a > img.id-provider, #signup-button').click(function(e){
if (!$('#chk-agree').attr('checked')) {
alert('Please accept our terms and conditions before continuing');
}
else {
alert('ok');
}
e.preventDefault();
});
});
</script>
The page is viewable here: http://jsfiddle.net/SrRAS/
On page B, the behaviour is as expected, i.e. a warning is issued when the checkbox is not checked before the signup button is clicked.
However, on page A, the warning is always shown, if even the checkbox has been manually clicked to make it checked.
Here is the FF console output (for both pages), when I was trying to understand what was going on:
>>> $('#chk-agree').attr('checked')
undefined
>>> $('input#chk-agree').attr('checked')
undefined
Eventually, on page A, I decided to programatically set the checked attribute (instead of manually clicking it – as a normal user would):
>>> $("input#chk-agree").click()
jQuery(input#chk-agree, input#chk-agree)
>>> $("input#chk-agree").attr('checked')
"checked"
When I then clicked the signup button on page A, it worked as expected (displayed an ‘ok’ message). However, when I manually unchecked the checkbox on page A, it still continued to display an ‘ok’ message. So it seems that for some reason, on page A, manually clicking on the checkbox does not toggle the ‘checked’ attribute.
I have two questions:
- Why is manually checking the checkbox not toggling the checkbox ‘checked’ attribute
- What would cause the code to work as expected on one page and not another?
[[Edit]]
I have also tried the following check instead of the one shown in my snippet above:
if (!$(this).is(':checked')/*!$('#chk-agree').attr('checked')*/) {
...
}else {
...
}
Now, at least the behaviour is consistent across both pages in that, none of the pages (A or B) seem to acknowledge when the checkbox is manually clicked – what on earth is going on?!
[[Edit2]]
The markup of the page that is not working is here: http://jsfiddle.net/SrRAS/
I will be very interested in finding out what is causing it not to work on this page.
Check out this version of your JsFiddle with Fixed code It contains two changes. checkboxes with unique IDs and correct jquery code for checked elements