[英]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.