Checkboxes "on" by default when not checked?

Viewed 219

I have a form page with 39 check box fields. I am trying to use javascript to get the value of them. Each checkbox has a name attribute of cb.

I am running:

function getBoxes() {
    let boxes = $('input[name="cb"]');
    for(let i = 0; i < boxes.length; i++) {
      console.log(boxes[i].value);
    }
  }

So I am getting an array of all of the checkbox inputs (they all have unique id's). If inside the loop I run console.log(boxes[i].value) it returns on for all 39 instances when NONE of them are in fact checked.

Anyone know what I'm doing wrong? I am expecting it to return 0 or off or NULL

Also here is an example of one of the checkboxes:

<input class="mx-2" type="checkbox" name="cb" id="cb_c">

All are the same they just have different id's

1 Answers

Switch this line:

console.log(boxes[i].value);

And give this a try instead:

console.log(boxes[i].checked);

That will tell you if the checkbox is checked or not when the code is run. The value of a checkbox will be something like on as that's the value that will be used if the checkbox has indeed been checked.

Related