繁体   English   中英

为什么 document.getElementById 不起作用,我需要改用 document.forms?

[英]why document.getElementById won´t work and I need to use document.forms instead?

我有这个简单的表单,我想检查文本输入是否为空。

所以这就是我所做的:

这是表格:

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

这是验证代码,在标签之后插入,当然,在标签之间:

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>

现在该代码根本不起作用。 它仅在我替换此行时才起作用:

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

对于这一行:

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

那么为什么不使用 .getElementById 呢?

您正在使用 ID 'tMonth'

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

但你试图把它当作 tmes

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

将上面的行更改为

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM