-2

How can i count the number of the selected checkboxes from this table:

<tbody>
    <tr>
        <td>
            <center>
                <form>
                    <input type="checkbox" value="<?php echo $rws['amount']; ?>" />
                </form>
            </center>
        </td>
    </tr>
</tbody>
11684
  • 7,356
  • 12
  • 48
  • 71
R.rere
  • 1
  • 2

1 Answers1

2

querySelectorAll lets you get a list of elements matching any CSS selector, so you can use that to get the checkboxes. You can use Array.prototype.reduce on it in order to count the number of them that are checked. So:

var count = Array.prototype.reduce.call(
    document.querySelectorAll("input[type=checkbox]"),
    function(sum, cb) {
        return sum + cb.checked ? 1 : 0;
    },
    0
);

The "array-like" part of this answer explains that use of Array.prototype.reduce that lets us treat the list from querySelectorAll as though it were an array when it isn't.

MDN has a description of how reduce works.

Graham
  • 7,431
  • 18
  • 59
  • 84
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875