I have one doubt that arose while I was trying to redirect to another page with submit.
Why if I replace the code for(var i=0;i...;i++)
with the line for(i in arreglo)
, in the redirection (onsubmit) only it shows alert('one')
instead of both, alert('one')
and alert('two')
?
<html>
<head>
<title>Registro Javascript</title>
<meta charset="utf-8"/>
<script type="text/javascript">
function inicio(){
document.getElementById("formulario").onsubmit=verificar;
}
function verificar(){
var arreglo=document.getElementsByTagName("input");
var camposVacios="";
var numVacios=0;
alert('one');
for(var i=0;i<arreglo.length;i++){
if(arreglo[i].getAttribute("type")=="text"){
if(arreglo[i].value.length==0){
camposVacios+="\n- "+arreglo[i].id;
numVacios=numVacios+1;
}
}
}
alert('two');
if(numVacios>0){
alert('Los siguientes campos estan sin completar : '+camposVacios);
return false;
}
return true;
}
function verificarObjeto(objeto){
if(objeto.value.length==0)
alert('El campo '+objeto.id+' debe tener al menos un caracter.');
}
</script>
</head>
<body onload="inicio()"> <br>
<form id="formulario" method="post" action="other.html"> <br>
Nombre : <input type="text" id="nombre" onblur="verificarObjeto(this)"/> <br>
Apellido Paterno: <input type="text" id="apellido paterno" onblur="verificarObjeto(this)"/> <br>
Apellido Materno: <input type="text" id="apellido materno" onblur="verificarObjeto(this)"/> <br>
Edad : <input type="text" id="edad" onblur="verificarObjeto(this)"/> <br>
Direccion : <input type="text" id="direccion" onblur="verificarObjeto(this)"/> <br>
Telefono : <input type="text" id="telefono" onblur="verificarObjeto(this)"/> <br>
Email : <input type="text" id="email" onblur="verificarObjeto(this)"/> <br>
<input type="submit" value="Registrarse"/>
<input type="reset" value="Limpiar campos"/>
</form>
</body>
</html>
The object you get with .getElementsByTagName
is not an array
but is a nodeList
. You have to turn it to an array before you put it in a loop to use more efficiently and in those cases i prefer .forEach
rather than for.
To make the array :
var array = Array.prototype.slice.call(arreglo);
To loop the array
array.forEach(function(elem){
if(elem.getAttribute("type")=="text"){
....