Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(this).checked not picking up checked boxes

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

like image 324
Sherman Szeto Avatar asked Nov 29 '22 00:11

Sherman Szeto


2 Answers

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

like image 156
Sterling Archer Avatar answered Dec 18 '22 21:12

Sterling Archer


$(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);
}
...
like image 32
qwertynl Avatar answered Dec 18 '22 22:12

qwertynl