1

Take the following scenario: you have 2 radio buttons, both with the same name, and both checked (I realize that's invalid):

<input type="radio" class="input" name="cb1" checked="checked" />
<input type="radio" class="input" name="cb1" checked="checked" />

Why do the following two selectors behave differently?

$('.input:checked').size(); // returns 1
$('.input[checked=checked]').size(); // returns 2

Apparently, the first selector returns only the checkbox that occurs last in the markup, while the first selector returns both.

jbyrd
  • 4,357
  • 7
  • 39
  • 75

2 Answers2

4

That's because :checked selector checks the checked property of the elements which is different from the checked attribute.

Community
  • 1
  • 1
undefined
  • 136,817
  • 15
  • 158
  • 186
  • 1
    **property**: Current *state* of the radio buttons (only one can be checked) – Samuel Liew Sep 09 '14 at 17:58
  • Thanks for the explanation and the SO link. [This comment specifically](http://stackoverflow.com/a/5884994/422845) was helpful in distinguishing between element attributes and properties. – jbyrd Sep 09 '14 at 18:15
2

Since both elements have the same name, they function as a single unit with only one radio button is actually selected at the time when elements are rendered.

enter image description here

.input[checked=checked] does not care about results, it just checks the attributes.

.input:checked reflect the actual element state.

Change names to differ, and both queries will return 2.

kornieff
  • 2,021
  • 15
  • 27