簡體   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