5

I have a function that is not picking up checkboxes correctly (if checked) with this function:

function playerJson() {
    players = [];
    $('input[name=playerCheckList]').each(function () {
        if ($(this).checked) {
            players.push($(this).val());
        }
    });

    return $.toJSON(players);
}

I use this function to check all buttons (correctly)

 $(function () {
    $("#checkAllPlayers").click(function () {
        $('input[name=playerCheckList]').each(function () {
            $(this).prop('checked', true);
        });
    });
});

If I don't have the if statement:

if ($(this).checked) 

from the first piece of code, it correctly picks up all the values (checked or not)

So, this statement is probably the problem, but I'm not sure why.

Thanks

3 Answers 3

15

That is referring to a jQuery object, which has no property 'checked' (The DOM would have that property though). You need to get the attribute value.

$(this).prop("checked");

Edit: I support qwertynl's answer because vanilla.js

2
  • 7
    or $(this).is(':checked') Commented Jan 14, 2014 at 20:51
  • 1
    Just a note: is() is slightly slower than prop() (attr() is the slowest) and are all slower than vanilla. Still, is() would work, of course. Commented Jan 14, 2014 at 20:55
9

$(this).checked does not work because $(this) is a jQuery oject.

Just look at the checked attribute of the DOM object (this):

...
if (this.checked) {
    players.push(this.value);
}
...
1
  • @BlackSheep I used no jQuery :-P
    – qwertynl
    Commented Jan 14, 2014 at 20:54
6

As the other answers say, .checked will not work on a jQuery object.

This is easier visualized this way:

$(this).checked returns undefined/error because it is a jQuery object, not an element.
$(this)[0].checked returns the value of checked because you are referencing the element itself, not the jQuery object referencing the element.

Below is a modified and fixed version of your script, eliminating the use of jQuery entirely for checked and for value as they are a pointless use of jQuery. The other use makes a little more sense, and so it will remain in my answer.

function playerJson() {
        players = [];
        $('input[name=playerCheckList]').each(function () {
            if (this.checked) {
                players.push(this.value);
            }
        });
        return $.toJSON(players);
    }
1
  • 2
    "$(this0[0].checked returns the value of checked", no it throws an error (not the downvoter.)
    – Ram
    Commented Jan 14, 2014 at 21:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.