我无法相信我找不到这个问题的答案,但我真的已经搜索过,找不到它!诚实!
无论如何 - 这是一个问题:我正在尝试为表单创建一个验证函数,如果该字段未验证,则不允许用户进入下一个表单字段。 我只是希望'不正确'字段具有焦点,直到它'正确'。
因为这是针对JS类的,所以我不能使用jQuery或任何其他框架。
这是一个HTML字段:
<li>Number 1:<input class="field2" type="text" id="star1" onchange="validateAndDraw(this.value);"></li>
这是JS函数的截断版本:
function validateAndDraw(theValue) {
if (isNaN(theValue)) {
alert("no good");
} else {
[do stuff here]
}
}
我尝试过使用'this.focus();'和'this.parentNode.focus();'但没有快乐。
我确信答案非常简单,但我似乎无法找到答案。
感谢, 贝内特
答案 0 :(得分:3)
尝试将对象引用发送给函数而不是值。
所以在你的输入事件中:
validateAndDraw(this);
并将您的功能更改为:
function validateAndDraw(input) {
if (isNaN(input.value)) {
alert("no good");
input.focus();
} else {
[do stuff here]
}
}
作为一方,我建议调查Progressive Enhancement。
答案 1 :(得分:0)
document.getElementById('star1').focus();
在函数中使用this
将返回函数。
或者,您可以在onclick
事件中传递对象:
<input class="field2" type="text" id="star1" onchange="validateAndDraw(this);">
所以功能看起来像
function validateAndDraw(obj) {
alert(obj.value);
}
答案 2 :(得分:0)
尝试在focus()
事件中调用blur
。
此外,函数中的this
指的是全局上下文,而不是元素
(它只引用内联处理程序中的元素;您从那里进行普通的函数调用)
您应该更改函数以接受元素作为参数(您可以在内联处理程序中将其作为this
传递)
答案 3 :(得分:0)
为什么不传入元素?
function validateAndDraw(theElement) {
var theValue = theElement.value;
if (isNaN(theValue)) {
alert("no good");
theElement.focus()
} else {
[do stuff here]
}
}
答案 4 :(得分:0)
发送作为触发器
表格中有每个循环函数用于检查输入。
如果有输入[x] .value =&#34;&#34;,请提醒并关注其中,下一个输入和下一个警报
<html>
<body>
<form onsubmit="return validateForm(this)">
Name: <input type="text" name="name"><br />
E-mail: <input type="text" name="email"><br />
Password: <input type="password" name="password"><br />
<input type="submit" value="Send">
</form>
<script >
function validateForm(input) {
for (x in input) {
if (input[x].value == "") {
alert(input[x].name + " must be filled out");
input[x].focus();
return false;
}
}
}
</script>
</body>
</html>
&#13;