Foros del Web » Programando para Internet » Javascript »

Posicionarse en campo vacio de un formulario

Estas en el tema de Posicionarse en campo vacio de un formulario en el foro de Javascript en Foros del Web. Hola, que tal? Tengo un formulario bastante largo en el cual uso Spry para verificar si el campo esta vacio o no. El problema es ...
  #1 (permalink)  
Antiguo 06/09/2010, 10:19
 
Fecha de Ingreso: julio-2010
Mensajes: 47
Antigüedad: 13 años, 9 meses
Puntos: 1
Posicionarse en campo vacio de un formulario

Hola, que tal? Tengo un formulario bastante largo en el cual uso Spry para verificar si el campo esta vacio o no.
El problema es que al ser bastante largo, si por ejemplo me falto rellenar el primer campo pero el resto estan completos y pongo enviar me sale el error de que faltan los datos pero al lado del campo (y no veo el error porque esta arriba), entonces me gustaria tambien que al presionar el boton me posicione en el lugar donde esta ese campo, ya que sino tendria que ir hacia arriba y es bastante molesto fijarse donde esta el error, ademas de que puede que algunos no se den cuenta que falto rellenar un campo y piensen que el formulario no anda.

Simplificando el problema: Necesito que si hay un campo sin rellenar (ademas de mostrar el error), me posicione ARRIBA (solo arriba ya que los campos obligatorios estan arriba de todo y abajo solo hay preguntas no obligatorias)

Como podria hacer esto? Espero sus respuestas y muchas gracias.

Saludos.
  #2 (permalink)  
Antiguo 06/09/2010, 10:59
Avatar de eits  
Fecha de Ingreso: junio-2005
Ubicación: valladolid, yucatán
Mensajes: 1.655
Antigüedad: 18 años, 10 meses
Puntos: 88
Respuesta: Posicionarse en campo vacio de un formulario

con la funcion focus() de javascript, ese te debe de ser útil.

saludos.
__________________
El amor es la locura mas lucida que tiene el hombre.- Andres Henestrosa
la tristeza no existe, solo es... la ausencia de la felicidad.

Última edición por eits; 06/09/2010 a las 11:04
  #3 (permalink)  
Antiguo 06/09/2010, 11:09
 
Fecha de Ingreso: abril-2010
Ubicación: Colombia
Mensajes: 229
Antigüedad: 14 años
Puntos: 2
Respuesta: Posicionarse en campo vacio de un formulario

podrias hacerlo con un focus.

document.form1.nombre.focus();

o simplemente con un ancla...
  #4 (permalink)  
Antiguo 06/09/2010, 12:45
 
Fecha de Ingreso: julio-2010
Mensajes: 47
Antigüedad: 13 años, 9 meses
Puntos: 1
Respuesta: Posicionarse en campo vacio de un formulario

Gracias, ya se que con un ancla puedo ubicarme en cualquier parte del documento, pero como lo aplico en este caso?
  #5 (permalink)  
Antiguo 06/09/2010, 15:43
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Tema movido desde PHP a Javascript
  #6 (permalink)  
Antiguo 06/09/2010, 16:09
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 11 meses
Puntos: 310
Respuesta: Posicionarse en campo vacio de un formulario

Código Javascript:
Ver original
  1. //pseudo-código
  2. if(!condicion){
  3.  campo.focus();
  4.  return false;
  5. }

Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #7 (permalink)  
Antiguo 07/09/2010, 10:22
 
Fecha de Ingreso: julio-2010
Mensajes: 47
Antigüedad: 13 años, 9 meses
Puntos: 1
Respuesta: Posicionarse en campo vacio de un formulario

Cita:
Iniciado por _cronos2 Ver Mensaje
Código Javascript:
Ver original
  1. //pseudo-código
  2. if(!condicion){
  3.  campo.focus();
  4.  return false;
  5. }

Saludos (:
Pero como deberia hacerlo, por ejemplo si mi campo de texto se llama "nombre"


Código Javascript:
Ver original
  1. if(nombre = null){
  2. nombre.focus();
  3. return false;
  4. }

como hago referencia al campo "nombre"?

Gracias.
  #8 (permalink)  
Antiguo 07/09/2010, 10:51
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 11 meses
Puntos: 310
Respuesta: Posicionarse en campo vacio de un formulario

Código HTML:
Ver original
  1. if(document.forms[0].elements['nombre'].value == null){
  2.  document.forms[0].elements['nombre'].focus();
  3.  return false;
  4. }
Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #9 (permalink)  
Antiguo 07/09/2010, 11:11
 
Fecha de Ingreso: julio-2010
Mensajes: 47
Antigüedad: 13 años, 9 meses
Puntos: 1
Respuesta: Posicionarse en campo vacio de un formulario

Hola! gracias por responder
Probe tu codigo pero solo me manda a otra pagina diciendo "Column 'Nombre' cannot be null"

Quiza no me explique bien antes...
Ya valide y puse los campos obligatorios con SPRY en Dreamweaver.
Los errores que aparecen si un campo esta vacio me aparecen en la misma pagina (al lado del campo)...
El problema que tengo es que el formulario es muy largo, y cuando pongo Enviar los errores que aparecen se ven arriba de todo y quiza alguno no se de cuenta de esto, por eso me gustaria que cuando pongan enviar, si un campo esta vacio me mande arriba de todo de la web donde estan los campos obligatorios....

es posible esto? o tendria que hacerlo de otra manera? muchas gracias por responder

Saludos.

Última edición por Pury; 07/09/2010 a las 11:38
  #10 (permalink)  
Antiguo 07/09/2010, 12:06
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 11 meses
Puntos: 310
Respuesta: Posicionarse en campo vacio de un formulario

Postea el código a ver si vemos dónde está el error.
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #11 (permalink)  
Antiguo 07/09/2010, 12:39
 
Fecha de Ingreso: julio-2010
Mensajes: 47
Antigüedad: 13 años, 9 meses
Puntos: 1
Respuesta: Posicionarse en campo vacio de un formulario

Código PHP:
<?php require_once('Connections/registro_preguntas.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  
$theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  
$theValue function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch (
$theType) {
    case 
"text":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;    
    case 
"long":
    case 
"int":
      
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case 
"double":
      
$theValue = ($theValue != "") ? "'" doubleval($theValue) . "'" "NULL";
      break;
    case 
"date":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;
    case 
"defined":
      
$theValue = ($theValue != "") ? $theDefinedValue $theNotDefinedValue;
      break;
  }
  return 
$theValue;
}
}

$editFormAction $_SERVER['PHP_SELF'];
if (isset(
$_SERVER['QUERY_STRING'])) {
  
$editFormAction .= "?" htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  
$insertSQL sprintf("INSERT INTO registro (Nombre, Apellido, Email, Ciudad, Preg1, Preg2, Preg3, Preg4, Preg5, Preg6, Preg7, Preg8, Preg9, Preg10, Preg11) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['nombre'], "text"),
                       
GetSQLValueString($_POST['apellido'], "text"),
                       
GetSQLValueString($_POST['email'], "text"),
                       
GetSQLValueString($_POST['ciudad'], "text"),
                       
GetSQLValueString($_POST['GrupoOpciones1'], "text"),
                       
GetSQLValueString($_POST['GrupoOpciones2'], "text"),
                       
GetSQLValueString($_POST['GrupoOpciones3'], "text"),
                       
GetSQLValueString($_POST['GrupoOpciones4'], "text"),
                       
GetSQLValueString($_POST['GrupoOpciones5'], "text"),
                       
GetSQLValueString($_POST['GrupoOpciones6'], "text"),
                       
GetSQLValueString($_POST['GrupoOpciones7'], "text"),
                       
GetSQLValueString($_POST['GrupoOpciones8'], "text"),
                       
GetSQLValueString($_POST['GrupoOpciones9'], "text"),
                       
GetSQLValueString($_POST['GrupoOpciones10'], "text"),
                       
GetSQLValueString($_POST['GrupoOpciones11'], "text"));

  
mysql_select_db($database_registro_preguntas$registro_preguntas);
  
$Result1 mysql_query($insertSQL$registro_preguntas) or die(mysql_error());

  
$insertGoTo "registro_ok.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$insertGoTo));
}

?>


<?php require_once('Connections/registro_preguntas.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Registro</title>
<style type="text/css">
<!--
.Estilo10 {
    color: #003300;
    font-size: 12px;
    font-family: Arial, Helvetica, sans-serif;
    font-weight: normal;
}
body {
    background-color: #E4FAED;
    background-repeat: repeat;
    background-image: url();
}
.Estilo14 {font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #336600; }
.Estilo20 {
    font-style: italic;
    font-size: 12px;
    font-weight: normal;
}
.Estilo22 {font-size: 16px}
#Layer1 {
    position:relative;
    width:202px;
    height:41px;
    z-index:1;
    left: 20px;
    top: 20px;
}
.Estilo9 {    color: #FFFFFF;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 10px;
}
.Estilo29 {font-size: 11px; color: #333333; }
.Estilo31 {font-family: Arial, Helvetica, sans-serif}
.Estilo32 {font-family: Arial, Helvetica, sans-serif; font-style: italic; }
-->
</style>
<script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>
<script src="SpryAssets/SpryValidationSelect.js" type="text/javascript"></script>
<script src="SpryAssets/SpryValidationRadio.js" type="text/javascript"></script>
<script type="text/JavaScript">
<!--
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
//-->
</script>
<link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" />
<link href="SpryAssets/SpryValidationSelect.css" rel="stylesheet" type="text/css" />
<link href="SpryAssets/SpryValidationRadio.css" rel="stylesheet" type="text/css" />
</head>

<body>
<table width="927" height="687" align="center" cellspacing="0">
  <tr>
    <th width="919" height="685" bgcolor="#FFFFFF" scope="col"><form action="<?php echo $editFormAction?>" method="POST" name="form1" id="form1">
        <table width="902" border="0" align="center" cellpadding="0" cellspacing="0" bordercolor="#FFFFFF">
          <tr>
            <th height="32" colspan="2" scope="col"><span class="Estilo31"><em>Registro</em></span></th>
          </tr>
          <tr>
            <td width="64" height="28" class="Estilo7"><div align="left" class="Estilo10"><span class="Estilo22">*</span>Nombre</div></td>
            <td width="831"><div align="left"><span id="sprytextfield1">
              <input name="nombre" type="text" id="nombre" size="30" />
            <span class="textfieldRequiredMsg">Ingrese su nombre</span></span></div></td>
          </tr>
          <tr>
            <td height="29" class="Estilo7"><div align="left" class="Estilo10"><span class="Estilo22">*</span>Apellido</div></td>
            <td><div align="left"><span id="sprytextfield2">
              <input name="apellido" type="text" id="apellido" size="30" />
            <span class="textfieldRequiredMsg">Ingrese su apellido</span></span></div></td>
          </tr>
          <tr>
            <td height="30" class="Estilo7"><div align="left" class="Estilo10"><span class="Estilo22">*</span>E-Mail</div></td>
            <td><div align="left"><span id="sprytextfield3">
            <input name="email" type="text" id="email" size="30" />
            <span class="textfieldRequiredMsg">Ingrese su e-mail</span><span class="textfieldInvalidFormatMsg">E-mail no válido.</span></span></div></td>
          </tr>
          <tr>
            <td class="Estilo7"><div align="left" class="Estilo10"><span class="Estilo22">*</span>Ciudad</div></td>
            <td><div align="left"><span id="spryselect1"><span class="selectInvalidMsg">Seleccione un pa&iacute;s</span></span></div>              <div align="left"><span id="sprytextfield4">
                <input name="ciudad" type="text" id="ciudad" size="30" />
            <span class="textfieldRequiredMsg">Ingrese su ciudad</span></span></div></td>
          </tr>
          
          <tr>
            <td height="19" class="Estilo7">&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
          <tr>
            <td height="26" class="Estilo7">&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
          <tr>
            <td height="26" colspan="2" class="Estilo20"> <div align="left" class="Estilo31"><br />
              <br />
            </div></td>
          </tr>
        </table>
            <table width="902" border="0" align="center" cellpadding="0" cellspacing="0" bordercolor="#DFF2DF">
              <tr>
                <th height="35" colspan="2" class="Estilo32" scope="col">Preguntas</th>
              </tr>
              <tr>
  #12 (permalink)  
Antiguo 07/09/2010, 12:43
 
Fecha de Ingreso: julio-2010
Mensajes: 47
Antigüedad: 13 años, 9 meses
Puntos: 1
Respuesta: Posicionarse en campo vacio de un formulario

Código PHP:
                <td width="811"><p align="left" class="Estilo10">1-Pregunta </p></td>
                <
td width="91"><div align="left">
                    <
p>
                      <
label>
                      <
input type="radio" name="GrupoOpciones1" value="Si" />
                      <
span class="Estilo10">Si</span></label>
                      <
label>
                      <
input type="radio" name="GrupoOpciones1" value="No" />
                      <
span class="Estilo10">No</span></label>
                      <
br />
                      <
label></label>
                    </
p>
                </
div></td>
              </
tr>
              <
tr>
                <
td><p align="left" class="Estilo10">2-Pregunta </p></td>
                <
td><div align="left">
                    <
p>
                      <
label>
                      <
input type="radio" name="GrupoOpciones2" value="Si" />
                      <
span class="Estilo10">Si</span></label>
                      <
span class="Estilo10">
                      <
label> </label>
                      </
span>
                      <
label>
                      <
input type="radio" name="GrupoOpciones2" value="No" />
                      <
span class="Estilo10">No</span></label>
                      <
br />
                    </
p>
                </
div></td>
              </
tr>
              <
tr>
                <
td><p align="left" class="Estilo10">3-Pregunta </p></td>
                <
td><div align="left">
                    <
p>
                      <
label>
                      <
input type="radio" name="GrupoOpciones3" value="Si" />
                      <
span class="Estilo10">Si</span></label>
                      <
label>
                      <
input type="radio" name="GrupoOpciones3" value="No" />
                      <
span class="Estilo10">No</span></label>
                    </
p>
                  <
label></label>
                </
div></td>
              </
tr>
              <
tr>
                <
td><p align="left" class="Estilo10">4-Pregunta </p></td>
                <
td><div align="left">
                    <
p>
                      <
label>
                      <
input type="radio" name="GrupoOpciones4" value="Si" />
                      <
span class="Estilo10">Si</span></label>
                      <
span class="Estilo10">
                      <
label> </label>
                      </
span>
                      <
label>
                      <
input type="radio" name="GrupoOpciones4" value="No" />
                      <
span class="Estilo10">No</span></label>
                    </
p>
                  <
label></label>
                </
div></td>
              </
tr>
              <
tr>
                <
td><p align="left" class="Estilo10">5-Pregunta </p></td>
                <
td><div align="left">
                    <
p>
                      <
label>
                      <
input type="radio" name="GrupoOpciones5" value="Si" />
                      <
span class="Estilo10">Si</span></label>
                      <
span class="Estilo10">
                      <
label> </label>
                      </
span>
                      <
label>
                      <
input type="radio" name="GrupoOpciones5" value="No" />
                      <
span class="Estilo10"No</span></label>
                    </
p>
                  <
label></label>
                </
div></td>
              </
tr>
              <
tr>
                <
td><p align="left" class="Estilo10">6-Pregunta </p></td>
                <
td><div align="left">
                    <
p>
                      <
label>
                      <
input type="radio" name="GrupoOpciones6" value="Si" />
                      <
span class="Estilo10">Si</span></label>
                      <
label>
                      <
input type="radio" name="GrupoOpciones6" value="No" />
                      <
span class="Estilo10">No</span></label>
                    </
p>
                  <
label></label>
                </
div></td>
              </
tr>
              <
tr>
                <
td><p align="left" class="Estilo10">7Pregunta </p></td>
                <
td><div align="left">
                    <
p>
                      <
label>
                      <
input type="radio" name="GrupoOpciones7" value="Si" />
                      <
span class="Estilo10">Si</span></label>
                      <
label>
                      <
input type="radio" name="GrupoOpciones7" value="No" />
                      <
span class="Estilo10">No</span></label>
                      <
br />
                    </
p>
                </
div></td>
              </
tr>
              <
tr>
                <
td><p align="left" class="Estilo10">8-Pregunta </p></td>
                <
td><div align="left">
                    <
p>
                      <
label>
                      <
input type="radio" name="GrupoOpciones8" value="Si" />
                      <
span class="Estilo10"Si</span></label>
                      <
label>
                      <
input type="radio" name="GrupoOpciones8" value="No" />
                      <
span class="Estilo10">No</span></label>
                      <
br />
                    </
p>
                </
div></td>
              </
tr>
              <
tr>
                <
td><p align="left" class="Estilo10">9-Pregunta </p></td>
                <
td><div align="left">
                    <
p>
                      <
label>
                      <
input type="radio" name="GrupoOpciones9" value="Si" />
                      <
span class="Estilo10">Si</span></label>
                      <
span class="Estilo10">
                      <
label> </label>
                      </
span>
                      <
label>
                      <
input type="radio" name="GrupoOpciones9" value="No" />
                      <
span class="Estilo10">No</span></label>
                      <
br />
                    </
p>
                </
div></td>
              </
tr>
              <
tr>
                <
td><p align="left" class="Estilo10">10-Pregunta </p></td>
                <
td><div align="left">
                    <
p>
                      <
label>
                      <
input type="radio" name="GrupoOpciones10" value="Si" />
                      <
span class="Estilo10">Si</span></label>
                      <
label>
                      <
input type="radio" name="GrupoOpciones10" value="No" />
                      <
span class="Estilo10">No</span></label>
                      <
br />
                    </
p>
                </
div></td>
              </
tr>
              <
tr>
                <
td><p align="left" class="Estilo10">11-Pregunta </p></td>
                <
td><div align="left">
                    <
p>
                      <
label>
                      <
input type="radio" name="GrupoOpciones11" value="Si" />
                      <
span class="Estilo10">Si</span></label>
                      <
label>
                      <
input type="radio" name="GrupoOpciones11" value="No" />
                      <
span class="Estilo10">No</span></label>
                      <
br />
                    </
p>
                </
div></td>
              </
tr>
              <
tr>
                <
td height="34" colspan="2"><div align="center">
                  <
input type="submit" name="Submit" value="Enviar" />
                </
div></td>
              </
tr>
        </
table>
            <
div align="left">
              <
p>&nbsp;</p>
      </
div>
                  
            <
input type="hidden" name="MM_insert" value="form1">
      </
form>
    </
th>
  </
tr>
</
table>
<
script type="text/javascript">
<!--
var 
sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1");
var 
sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2");
var 
sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3""email");
var 
spryselect1 = new Spry.Widget.ValidationSelect("spryselect1", {isRequired:falseinvalidValue:"-1"});
var 
sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4");
//-->
//CODIGO DE _cronos2
if(document.forms[0].elements['nombre'].value == null){
 
document.forms[0].elements['nombre'].focus();
 return 
false;
}
</script>

</body>
</html> 


Este es el codigo

El codigo que me pasaste lo ubique ahi abajo....iria ahi?

gracias
  #13 (permalink)  
Antiguo 07/09/2010, 14:27
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 11 meses
Puntos: 310
Respuesta: Posicionarse en campo vacio de un formulario

Prueba así:
Código Javascript:
Ver original
  1. var exp = /\s*/;
  2. var campo = document.forms[0].elements['nombre'];
  3. if (exp.test(campo.value) || campo.value == ''){
  4.  campo.focus();
  5.  return false;
  6. }
Pero el código lo tienes mal, o sea, todas las validaciones de campos que tengas que hacer las deberías meter en un función, y en el onsubmit del form poner 'return funcion();', aunque yo de Spry no sé y se tiene que hacer, pero por lo menos para los campos esos que necesitas que haya foco, mételos en una función como te dije.
Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red

Última edición por _cronos2; 07/09/2010 a las 14:38

Etiquetas: vacio, formulario, campos
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 05:40.