如果出现错误,则阻止表单提交
基本上,我有一个代码,如果用户编写的 ID 已经存在或太短,则向用户显示错误,但问题是我无法弄清楚如何防止出现错误的表单提交。
需要弹出警报窗口的代码:
jQuery("#submit").click(function(e){
if(error === '1')
{
alert("There are some errors in the form.");
e.preventDefault();
}
});
然后我使用 AJAX 得到答案并显示错误:
if(msg == 'OK')
{
var error = '0';
}
else
{
var error = '1';
jQuery("#idCheck_msg").slideDown("fast");
jQuery("#idCheck_text").text(msg).slideDown("fast");
}});
}
我尝试使用 var error
执行某些操作,但 Firebug 说错误未定义并且形式即使出现错误,get 也会提交。
有什么帮助吗? ;)
Basically i have a code that shows the user an error if the ID he wrote already exist or is too short but the problem is i can't figure out how to prevent the form from submission where there there is an error.
The code that needs to popup an alert window:
jQuery("#submit").click(function(e){
if(error === '1')
{
alert("There are some errors in the form.");
e.preventDefault();
}
});
Then i get the answer using AJAX and showing up the error:
if(msg == 'OK')
{
var error = '0';
}
else
{
var error = '1';
jQuery("#idCheck_msg").slideDown("fast");
jQuery("#idCheck_text").text(msg).slideDown("fast");
}});
}
I have tried to do something with var error
but Firebug says that error is not defined and the form get's submitted even when there is an error.
Any help? ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
error
定义为全局变量。即在使用变量之前删除var
:Define
error
as a global variable. That is removevar
before using the variable:您似乎在提交表单之后设置
error
的值,但在提交表单之前检查它的值。鉴于您帖子中的代码,当您尝试检查它的值时,
error
将是未定义的。此外,提交表单后,error
仍将是未定义的,因为您使用var
关键字在 AJAX 响应处理程序的范围内声明它。如果您在设置
error
的值时从 AJAX 处理程序中删除var
关键字,您的提交逻辑应该会在第二次起作用。底线:
error
的值需要在提交表单之前设置,而不是在 AJAX 响应处理程序中设置。It appears that you're setting the value of
error
after the form is submitted but checking it's value before the form is submitted.Given the code in your post,
error
will be undefined when you attempt to check it's value. In addition, after the form is submitted,error
will still be undefined because you're declaring it within the scope of your AJAX response handler using thevar
keyword.If you remove the
var
keyword from your AJAX handler when setting the value oferror
, your submission logic should work the second time around.Bottom Line: The value of
error
needs to be set before your form is submitted, not in the AJAX response handler.AJAX 调用是什么时候进行的?在收到 AJAX 调用的成功响应之前,您将无法检查“错误”。此外,您还需要删除“var”,使其处于全局范围内。
如果提交表单时也进行 AJAX 调用,则需要将错误检查移至处理 AJAX 响应的代码内部。
When is the AJAX call made? You won't be able to check 'error' until you get a success response from the AJAX call. Also you need to remove 'var' so it is in global scope.
If your AJAX call is also made when the form is submitted, you will need to move the error check to inside the code that handles the AJAX response.