JS var 声明 - 由于变量保持相同值的函数问题导致错误的验证
我正在对表单“文本输入”进行验证。 如果用户将输入留空,则函数将开始运行。如果该字段大于 1 - 那么它不会进入该函数。
问题是: 第一次,用户将输入留空,函数运行,我收到了警报 - 没关系。 第二次,用户在 AGE 输入中添加了 10 - 他再次收到警报 - 但他不应该这样做。
笔记: 年龄输入值,从不同的函数(计算)返回到名为:result 的 var。
这是代码:
$(document).ready(function(){
$('#btn_send').click(function(){
//var result gets the value ffrom another function of input "Age" value. -> return thisform.Age.value
var result = calc(document.getElementById("campaignform"));
if (result<1)
{
$("#campaignform").submit(function(event) {
event.preventDefault(); alert ("prevent default");
});
}
else{
return true;
};
});
});
因此,如果您第二次尝试单击“提交”,则会进入 $('#btn_send').click(function() ,即使您在 AGE(作为结果返回)输入中添加了例如 67,您也会进入IF 语句是: if (result<1)
我对开发还很陌生,所以我希望你能理解我。 抱歉,如果我有错误。 你能建议这个问题的更好的标题是什么吗?
提前致谢, 沙伊
I am doing a Validation for Form "Text input".
If the user leaves the input empty, a function is starting to run. If the field is bigger than 1 - so it doesn't get into the function.
The problem is:
The first time, the user left the input empty, function ran, and I got the alert - that's OK.
Second time, The user added 10 in the AGE input - And again he gets the Alert - But he should not.
Note:
Age input value, returns from a different function (calc) to a var called: result.
this is the code:
$(document).ready(function(){
$('#btn_send').click(function(){
//var result gets the value ffrom another function of input "Age" value. -> return thisform.Age.value
var result = calc(document.getElementById("campaignform"));
if (result<1)
{
$("#campaignform").submit(function(event) {
event.preventDefault(); alert ("prevent default");
});
}
else{
return true;
};
});
});
so if you try the second time to click on Submit, then you get into $('#btn_send').click(function() and eventhough you added for example 67 in the AGE (return as result) input, you get into the IF atatement which is: if (result<1)
I'm pretty new to developing, so I hop you will understand me.
Sorry if I have mistakes.
Can you advice what could be a better TITLE for this question?
thanks in advance,
Shai
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
向表单添加一个事件处理程序,以便将来每次提交表单时,都会调用该函数。您再也不会删除该事件处理程序,因此即使在更正该字段之后,每次提交时仍会调用默认阻止函数。
可以使用 unbind 方法删除 jQuery 事件处理程序,但通常最好避免大量添加和删除处理程序。更简单,也更可靠,因为捕获按钮点击可能无法获取所有表单提交,因此在一个静态
submit
事件处理程序中完成所有操作,例如:Adds an event handler to the form so that every time it gets submitted in future, the function gets called. You never remove that event handler again, so even after the field is corrected the default-preventing function will still get called on every submit.
jQuery event handlers can be removed using the unbind method, but generally it's better to avoid lots of adding and removing handlers. Easier—and also more reliable, since catching button clicks can fail to pick up all form submissions—is to do everything in one static
submit
event handler, eg: