表单字段验证不起作用
我有一些表单验证代码似乎无法正常工作,但我不明白为什么。
function isTextFieldEmpty(textField){
//return true or false depending on whether or not there is any text in the field
console.log("Checking to see if the current field is empty...");
var val = textField.value; //val is the text from the current field
console.log("The current value of 'val' is: " + val);
if(val.length < 1){
return true;
}else{
return false;
}
}
我得到的错误是:“未捕获的类型错误:无法读取未定义的属性‘长度’”。果然,我的控制台日志显示“val”的值是未定义。
我确信我错过了一些东西,但我仍在学习 JS,不知道它是什么。有什么建议吗?
编辑:这是我传递给函数的内容:
var uName = document.getElementById("unionname");
var noUnionName = isTextFieldEmpty(uName);
“unionname”是我尝试验证的文本字段的 id。这是相关的 HTML:
<div class="formBox">
<label for="unionname">Union Name</label>
<input type="text" name="unionname" id="unionname" value="" class="wide"/>
<span class="feedback good">Sample good message</span>
</div>
I've got some form verification code that doesn't seem to be working correctly, and I can't figure out why.
function isTextFieldEmpty(textField){
//return true or false depending on whether or not there is any text in the field
console.log("Checking to see if the current field is empty...");
var val = textField.value; //val is the text from the current field
console.log("The current value of 'val' is: " + val);
if(val.length < 1){
return true;
}else{
return false;
}
}
The error I get is: "Uncaught TypeError: Cannot read property 'length' of undefined". Sure enough, my console log says that the value of 'val' is undefined.
I'm sure I'm missing something, but I'm still learning JS and can't figure out what it is. Any suggestions?
Edit: Here is what I'm passing to the function:
var uName = document.getElementById("unionname");
var noUnionName = isTextFieldEmpty(uName);
'unionname' is the id of the texfield that I'm trying to validate. Here is the relevant HTML:
<div class="formBox">
<label for="unionname">Union Name</label>
<input type="text" name="unionname" id="unionname" value="" class="wide"/>
<span class="feedback good">Sample good message</span>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在该函数中本地声明
var val
。尝试通过将其放在脚本的顶部来全局声明它;不需要设置,只需声明即可。You are declaring
var val
locally in that function. Try declaring it globally by putting it at the top of your script; don't need to set it, just declare it.我已经让它工作了。看来验证功能没问题;问题出在我调用它的方式上。
这就是我最终调用该函数的方式。
具有讽刺意味的是,我在上一个示例中遗漏的错误 .onblur 代码似乎可能是导致我的问题的原因。但我真的不确定。
I've gotten it working. Seems that the validation function was fine; the problem was in the way I was calling it.
This is how I ended up calling the function.
Ironically, it seems that the faulty .onblur code that I left out of my previous example may have been the cause of my problem. But I'm really not sure.