[英]why document.getElementById won´t work and I need to use document.forms instead?
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:所以这就是我所做的:
<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>
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?那么为什么不使用 .getElementById 呢?
You're using the ID 'tMonth'您正在使用 ID 'tMonth'
<input id='tMonth' value='<?php echo $tMonth;?>' name='tmes' type='text'>
but you're trying to get it as tmes但你试图把它当作 tmes
var tMonth=document.getElementById('tmes');
change the above line to将上面的行更改为
var tMonth=document.getElementById('tMonth');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.