0

im having a strange problem with a jquery click function. What is suppose to happen is the user clicks a link '.selectlink' and it ticks a box on the page. This works just fine, click it again and it unticks the box.....also fine, click the link once more and nothing at all happens, click it some more and still nothing happens, so the function only seems to work after two clicks then stops working until the page is refreshed.

$(document).on('click', '.selectlink', function () {
     var myId = $('#check_' + this.id);

     if ($(myId).is(':checked')) {
          $(myId).attr('checked', false);
     } else {
          $(myId).attr('checked', true);
     }

     countChecked();
});
5
  • 4
    If it is a checkbox, you really should be using prop and not attr. Commented Sep 24, 2013 at 9:20
  • It is working well... jsfiddle.net/zqf3S Commented Sep 24, 2013 at 9:21
  • 1
    What does countChecked() do? Commented Sep 24, 2013 at 9:22
  • countchecked looks to see how many boxes on the page have been ticked and displays it as a number at the top of the page. Commented Sep 24, 2013 at 9:23
  • stackoverflow.com/questions/18977446/… How many times are we asking this today? Commented Sep 24, 2013 at 9:58

3 Answers 3

1

The problem arises because the ':checked' state is determined based on the 'checked' property in the DOM, not the presence, or value of the 'checked' attribute. See the jquery docs for more info on properties vs. attributes: http://api.jquery.com/prop/

In order for it to work (as you have discovered) you have do do this:

var myId = $('#check_' + this.id);
if ($(myId).is(':checked')) {
    $(myId).prop('checked', false);
} else {
    $(myId).prop('checked', true);
}
Sign up to request clarification or add additional context in comments.

Comments

0

How strange, I have found if I use prop instead of attrib it works more than twice now, not idea why ?.

$(document).on('click', '.selectlink', function () {
     var myId = $('#check_' + this.id);
     if ($(myId).is(':checked')) {
         $(myId).prop('checked', false);
     }
     else {
        $(myId).prop('checked', true);
     }
     countChecked();
    });
});

1 Comment

attr() might not accept boolean 2nd param. Did you try 0/1 instead?
0

try

$(document).off('click').on('click', '.selectlink', function () {

unbind and bind.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.