0

I have this in a form:

<input class="form-check-input" type="checkbox" id="pago[1][8819]">
<input class="form-check-input" type="checkbox" id="pago[2][5241]">
<input class="form-check-input" type="checkbox" id="pago[3][8541]">

How do I grab these in order to do a loop?

I've tried:

const pago = document.querySelector('#pago');

for (let i = 0; i < pago.length; i++) {
  const element = array[i];
  console.log(element);
}

But It does not work (returns NULL).

Edit:

I've read this reply here, but in this case I shouldn't need to use regex to resolve this. I think it should get sorted with a loop of some kind. In that question, the problem was to find elements that have certain strings in their names, where in this case, I need to loop through numbers.

Rosamunda
  • 14,620
  • 10
  • 40
  • 70
  • Does this answer your question? [querySelector, wildcard element match?](https://stackoverflow.com/questions/8714090/queryselector-wildcard-element-match), specifically `[id^='someId'] will match all ids starting with someId` – James Aug 16 '21 at 11:17
  • 2
    You can never use a for loop when you select a element by ID, ids's are unique for the page, this the id attribute needs to be the name attribute, use `.form-check-input` in your querySelectorAll (or give them another class) – Gert B. Aug 16 '21 at 11:17
  • Don't use querySelector when you want to select more than one element, use querySelectorAll. – James Aug 16 '21 at 11:18
  • @GertB. _"You can never use a for loop when you select a element by ID..."_ - That's not quite right. Yes, ids should be unique. But you're not forced to use `.getElementById()` or `.querySelector()` with an id selector. `.querySelectorAll('input[id^="pago["]')` (+ `.forEach()` or a `for` loop) would definitely work – Andreas Aug 16 '21 at 11:21
  • @Andreas Ok thats true, but the `[]` characters don't belong in a `id` attribute. – Gert B. Aug 16 '21 at 11:24
  • @GertB. That's only true for [HTML 4.x but not anymore for HTML5](https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html) – Andreas Aug 16 '21 at 11:30

1 Answers1

3

You can try using attribute starts with ([attr^=value]) selector:

const pago = document.querySelectorAll('[id^=pago]');

for (let i = 0; i < pago.length; i++) {
  const element = pago[i];
  console.log(element);
}
<input class="form-check-input" type="checkbox" id="pago[1][8819]">
<input class="form-check-input" type="checkbox" id="pago[2][5241]">
<input class="form-check-input" type="checkbox" id="pago[3][8541]">
Mamun
  • 66,969
  • 9
  • 47
  • 59