[英]parseInt(x,10) causing max callstack/too much recursion error
I have a simple JS function that updates a hidden textbox based on 2 input values. 我有一个简单的JS函数,它根据2个输入值更新一个隐藏的文本框。
Before I update the hidden text box, I use the the parseInt(x,10) to validate that input is numeric, if not I set the value to 0. 在更新隐藏的文本框之前,我使用parseInt(x,10)来验证输入是否为数字,如果没有,则将该值设置为0。
Why is this causing a too much recursion error? 为什么这会导致过多的递归错误?
$(function () {
$("#payment-form").on("submit",function (e) {
var xDollars = $("#dollars").val();
var xCents = $("#cents").val();
//collect our form dollar and cents values, set to 0 if not int
if (parseInt(xDollars, 10) == "NaN") {
$("#dollars").val("0");
}
if (parseInt(xCents, 10) == "NaN") {
$("#cents").val("00");
}
//join dollars and cents and submit transaction amount
$("#TransactionAmount").val(xDollars + "." + xCents);
$("#payment-form").submit();
return true;
});
});
It's not parseInt()
that's causing your problem, it's this: 不是
parseInt()
会引起您的问题,而是这样的:
$("#payment-form").submit();
You're triggering the "submit" action from inside the "submit" handler. 您正在从“提交”处理程序内部触发“提交”操作。
If you just return true
if validation succeeds, the form should submit normally. 如果验证成功后仅返回
true
,则表单应正常提交。
That's because jQuery does not differentiate whether you are submitting a form via a submit
event or via .submit()
method. 这是因为jQuery不区分无论您是通过提交表单
submit
事件或通过.submit()
方法。 Therefore, if you use jQuery's $.submit()
, it will fire a submit
event manually. 因此,如果你使用jQuery的
$.submit()
它会触发一个submit
手动事件。
Use vanilla-js instead. 请改用vanilla-js。 According to Form submission algorithm , that event won't be fired if you use
.submit()
: 根据表单提交算法 ,如果您使用
.submit()
,则不会触发该事件:
If the submitted from
submit()
method flag is not set, then fire a simple event that bubbles and is cancelable namedsubmit
, at form .如果未设置来自
submit()
方法的 Submit标志,则在form处引发一个简单的事件 ,该事件会冒泡并且可以取消,名为submit
。 If the event's default action is prevented (ie if the event is canceled) then abort these steps.如果阻止了事件的默认操作(即,如果事件被取消),则中止这些步骤。 Otherwise, continue (effectively the default action is to perform the submission).
否则,请继续(实际上,默认操作是执行提交)。
Therefore, this wouldn't be problematic: 因此,这不会有问题:
document.getElementById('payment-form').submit();
But in this case you can just remove $("#payment-form").submit();
但是在这种情况下,您只需删除
$("#payment-form").submit();
. 。 If you don't cancel the event, the form should be submitted automatically.
如果您不取消活动,则应自动提交表单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.