Why clicking on checkbox does not add the attribute checked='checked'

30,278

Solution 1

What are you trying to do? Find out if its checked?

$('.user_roles').click(function(){ 
    console.log( $(this).is(':checked'));
});

http://jsfiddle.net/petersendidit/FCrSg/1/

Solution 2

The HTML attribute checked means: checked by default, when the page loads. This won't change when the checkbox is clicked.

<input type="checkbox" checked="checked"> <!-- The HTML attribute -->

The DOM property checked is actually the current state of the checkbox and is either true/false. This will change when the checkbox is clicked, but isn't visible when you inspect the HTML.

$('input:check')[0].checked == true;
// Whether or not the checkbox is currently checked

Solution 3

If you want to see it appear on the element displayed in the console, use the native setAttribute() method.

Example: http://jsfiddle.net/FCrSg/2/

this.setAttribute('checked',this.checked);

So it would look like this:

$('.user_roles').click(function(){
    this.setAttribute('checked',this.checked);
    console.log( $(this) );
});

Then the console should give you:

<input class=​"user_roles" type=​"checkbox" checked=​"true">​

Though you normally wouldn't need the attribute set like that. Typically the property is enough.

Share:
30,278

Related videos on Youtube

felix
Author by

felix

Updated on July 09, 2022

Comments

  • felix
    felix almost 2 years

    When I click a checkbox, why does checked attribute is not getting added?. You can see the code here http://jsfiddle.net/FCrSg/

  • Tim Down
    Tim Down over 13 years
    This is the answer. Forget about attributes.
  • damon
    damon about 8 years
    above solution work for me perfectly fine but i used also prop() function that was also work perfectly fine but for same code dose not work whats the reason behind it please tell me
  • Admin
    Admin almost 8 years
    This response does not actually answer the question.
  • ADJenks
    ADJenks almost 6 years
    Can you please cite your references?
  • vgrinko
    vgrinko about 4 years
    are there any references? would much appreciate if you could share.
  • Rich Court
    Rich Court over 2 years
    I'm sure everyone's moved on from this by now, but for the people asking for references: developer.mozilla.org/en-US/docs/Web/HTML/Element/input/…