Something very strange happens to me that I don't see any sense in it.
I have a for loop in javascript that always skips iteration 4. The code is very long, I leave you only the fragment where I detect the error.
I add a bit of info: I have a previous function that generates inputs in this way:
<input type="hidden" name="ref_X" value="2" id="ref_X">
<input type="hidden" name="unidades_X" id="uni2_X" value="1">
<input type="hidden" name="precio_X" value="3" id="pre2_X">
<input type="hidden" name="id_X" id="id_X" value="9299984">
<input type="hidden" name="nombre_X" id="nombre_X" value="Prueba 2">
<input type="hidden" name="iva_X" id="iva_X" value="21">
Where X is a counter (every time I generate the above block, the counter is incremented).
After creating each block I pass to the for below which iterates through all the input blocks to save them and update other data.
The case is that block 4 contains all the info and does not read the input id="iva_4":
<input type="hidden" name="iva_4" id="iva_4" value="21">
but if the rest of the same block 4.
Block for:
for(var a=1; a<=contador; a++){
unidades = document.getElementById('uni2_'+a).value;
precio = document.getElementById('pre2_'+a).value;
total = parseFloat(total) + (parseFloat(unidades)*parseFloat(precio));
nombre = document.getElementById('nombre_'+a).value;
iva = document.getElementById('iva_'+a).value;
alert(a+"->"+document.getElementById('iva_'+a).value);//Da undefined
alert(a+"->"+document.getElementById('nombre_'+a).value);//Si lo muestra
}
And what is really there at that moment is:
<input type="hidden" name="ref_4" value="2" id="ref_4">
<input type="hidden" name="unidades_4" id="uni2_4" value="1">
<input type="hidden" name="precio_4" value="3" id="pre2_4">
<input type="hidden" name="id_4" id="id_4" value="9299984">
<input type="hidden" name="nombre_4" id="nombre_4" value="Prueba 2">
<input type="hidden" name="iva_4" id="iva_4" value="21">
Makes sense? The rest of the interactions if you do them correctly.
PS: Solved, I had another one with the id="iva_4"...!!
Your loop works, it shouldn't skip 4, maybe you have a bug in some other part of the code that you haven't posted, but the loop in the question works for me:
Check out the browser's dev console and you can use it to test bits of code you think give errors, as well as the tools it has for debugging etc. In the console you should have errors and warnings that would be helpful.
EDIT: With the changes added to the question, it still works, I put an HTML element as you indicate (only 4) and using your same code to access the vat it works:
EDIT: In the end the problem was a span with the same ID. Surely it was before, it found it before and that way the input was not really accessed.