Pergunta

I have this simple form, and I want to check out that the text input isn´t left empty.

So this is what I´ve done:

This is the form:

<form onsubmit='return validar()' name="miForm" action="" method="POST">
<input id='tMonth' value='<?php echo $tMonth;?>' name='tmes' type='text'>  
...

And here´s the validation code, inserted right after the tag, and in between a tag, of course:

function validar()
{
    mostrarValidacion=document.getElementById('mostrarValidacion');
    error=false;
    mensaje='';   
    var tMonth=document.getElementById('tmes');
if (!tMonth)  {
  mensaje += 'Debe completar todos los campos<br>';
  error=true;
  }
mostrarValidacion.innerHTML=mensaje; 
  if (error==true) {
      //con un return false nunca manda al servidor nada, no hace nada.
      return false;
  } else {
      return true;
  }  
}
</script>

Now that code isn´t working at all. It only worked when I replaced this line:

var tMonth=document.getElementById('tmes');

For this line:

var tMonth=document.forms["miForm"]["tmes"].value

So why isn´t working with .getElementById?

Foi útil?

Solução

You're using the ID 'tMonth'

<input id='tMonth' value='<?php echo $tMonth;?>' name='tmes' type='text'>

but you're trying to get it as tmes

var tMonth=document.getElementById('tmes');

change the above line to

var tMonth=document.getElementById('tMonth');
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top