0

I am using jquery to select checkbox on and off when user click on image.

Here is my code:

function clickimage(e){
    chkbox = e.parent().children('.chkBox');
    if(chkbox.is(":checked")){
        chkbox.attr('checked', false);
    }else{
        chkbox.attr('checked', true);
    }
}

When I first click on image, the checkbox does checked. When I click on image again, the checkbox is unchecked. But the problem is after that, the checkbox will never be selected again.

I try to verify chkbox.is(":checked") and it does return false value. I put the checking code after chkbox.attr('checked', true);, it also return false value.

Why is it like that? How can I fix it?

Thank you.

1
  • 1
    can you share the html Commented Apr 13, 2014 at 13:36

4 Answers 4

2

Do this:

function clickimage(e){
    chkbox = e.parent().children('.chkBox');
    if(chkbox.is(":checked")){
        chkbox.prop('checked', false);
    }else{
        chkbox.prop('checked', true);
    }
}

You should use .prop() and not .attr()

Sign up to request clarification or add additional context in comments.

Comments

1

You do not need Javascript for this.

Just put the image into a label.

Fiddle here

2 Comments

Thanks for your answer. I tried with label. But it doesn't work well on IE8 for my case. That's why I am thinking to use javascript to do the job.
No problem. I think this question with provided accepted answer is of interest for you then: stackoverflow.com/questions/15740206/…
0

Try

if(chkbox.is(":checked")){
    chkbox.removeAttr('checked');
}else{
    chkbox.attr('checked', 'checked');
}

Comments

0

Try this:

 function clickimage(e){
  chkbox = e.parent().find('.chkBox');
  if(chkbox.is(":checked")){
     chkbox.attr('checked', false);
   }else{
      chkbox.attr('checked', true);
   }
 }

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.