Javascript 表单字段验证不起作用
我有一些表单验证代码,似乎不能正常工作,我不知道为什么Javascript 表单字段验证不起作用,javascript,forms,variables,verification,Javascript,Forms,Variables,Verification,我有一些表单验证代码,似乎不能正常工作,我不知道为什么 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
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;
}
}
“unionname”是我试图验证的texfield的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>
工会名称
好消息示例
您正在该函数中本地声明var val
。尝试通过将其放在脚本顶部来全局声明它;不需要设置它,只需声明它。我已经让它工作了。似乎验证功能很好;问题在于我怎么称呼它
window.onload = justDoIt;
function justDoIt() {
var uName = document.getElementById("unionname");
uName.onblur = function(){
clearMessages(uName); // clear out old feedback for this field
var noUnionName = isTextFieldEmpty(uName);
这就是我最终调用函数的原因
具有讽刺意味的是,我在前面的示例中遗漏的错误的.onblur代码可能是我的问题的原因。但我真的不确定。似乎还可以。。。你确定你正在传递的参数实际上包含一个文本字段吗?@Andrea它似乎不是。。。嗯。那不太好。你给你的
isTextFieldEmpty()
函数传递了什么?这对我来说非常好。您是否确保等待DOM准备好调用您的函数?您可以发布您正在使用的相关HTML吗?@GnomeSlice是您试图验证的文本字段上的id
属性值的unionname
?但我只需要在该函数中使用它。我不应该在全球范围内申报。
window.onload = justDoIt;
function justDoIt() {
var uName = document.getElementById("unionname");
uName.onblur = function(){
clearMessages(uName); // clear out old feedback for this field
var noUnionName = isTextFieldEmpty(uName);