Rosamunda
Rosamunda

Reputation: 14990

How do I grab an id element in a form that is constructed as an array in Javascript?

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.

Upvotes: 0

Views: 50

Answers (1)

Mamun
Mamun

Reputation: 68923

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]">

Upvotes: 3

Related Questions