incomplete rows in JS with FOR cycle

1

If there are 50 rows, why does JS run 49 rows? this is my code

var todoCorrecto = true;
var formulario = document.enviaComision;
for (var w = 1; w < formulario.length; w++) {
  if (formulario[w].type == 'text') {
    if (formulario[w].value == "") {
      console.log(w);

      todoCorrecto = false;
    }
  }
}

How would you make it go through the 50 rows?

    
asked by Ivxn 28.05.2016 в 00:16
source

2 answers

2

The indexes of arrays in JavaScript begin in 0 no in 1 . Therefore you must initialize var w = 0 in for

var todoCorrecto = true;
var formulario = document.enviaComision;
for (var w = 0; w < formulario.length; w++) {
  if (formulario[w].type == 'text') {
    if (formulario[w].value == "") {
      console.log(w);

      todoCorrecto = false;
    }
  }
}
    
answered by 28.05.2016 / 00:52
source
1

Maybe var formulario = document.enviaComision; is an array and at the moment of crossing it you are not starting var w = 0; in the cycle for for (var w = 1; w < formulario.length; w++) { Try changing it to 0 the variable w.

But in the same way I'll give you another example, I hope it works for you:

var a = document.querySelectorAll("form input[type='text']"); //buscamos todos los input's de tipo text que esten dentro del form
for(var b in a) // como nos entrega un Array, entonces recorremos ó iteramos
{
  var c = a[b];
  if(typeof c == "object"){ //verificamos que todo sea un objeto
    console.log(a.item(b),b); // Imprimimos el item de la posición b y tambien la posición del array b.
  }
}
<form name="miformulario">

  <input type="text" name="uno" />
  <input type="text" name="dos" />
  <input type="text" name="tres" />
  <input type="text" name="cuatro" />
  <input type="text" name="cinco" />
  <input type="text" name="seis" />
  <input type="text" name="siete" />
  <input type="text" name="ocho" />
  <input type="text" name="nueve" />
  <input type="text" name="diez" />
</form>
    
answered by 28.05.2016 в 00:34