在 AJAX 回调中取消绑定提交事件
如果未选中复选框,我会发出警报并阻止表单提交(单击提交按钮或 Enter)并绑定 false。我需要在 AJAX 回调中取消绑定,但无法执行此操作。
HTML:
<form action="act.php" onsubmit="formSubmit()" id="TypeForm" name="TypeForm" method="POST">
<label>
<input type="radio" name="Type" value="1">
<span>Type 1</span>
</label>
<label>
<input type="radio" name="Type" value="2">
<span>Type 2</span>
</label>
<input type="submit" name="submit" id="submit" value="Next" />
</form>
Javascript/JQuery:
<script>
function formSubmit() {
var self=this;
$(self).bind('submit', false);
if ($('#TypeForm').find('input:radio:checked').length == 0) {
alert('A selection is required.');
} else {
$.ajax({
type: "POST",
url: "add.php",
success: function() {
$(self).unbind();
}
});
}
}
</script>
提前感谢您的帮助!
If a checkbox is not checked, I alert and prevent form submission (either submit button click or Enter) with bind false. I need to unbind in the AJAX callback, but am unable to do so.
HTML:
<form action="act.php" onsubmit="formSubmit()" id="TypeForm" name="TypeForm" method="POST">
<label>
<input type="radio" name="Type" value="1">
<span>Type 1</span>
</label>
<label>
<input type="radio" name="Type" value="2">
<span>Type 2</span>
</label>
<input type="submit" name="submit" id="submit" value="Next" />
</form>
Javascript/JQuery:
<script>
function formSubmit() {
var self=this;
$(self).bind('submit', false);
if ($('#TypeForm').find('input:radio:checked').length == 0) {
alert('A selection is required.');
} else {
$.ajax({
type: "POST",
url: "add.php",
success: function() {
$(self).unbind();
}
});
}
}
</script>
Thanks in advance for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许您忘记了事件名称 -
$(self).unbind('submit');
?Maybe you forgot event name -
$(self).unbind('submit');
?您想在用户按 Enter 或单击提交按钮时停止正常提交表单吗?然后您需要阻止
事件
采取默认操作。试试这个:编辑:正如Trevor提到的,您应该使用jQuery来绑定您的函数,以便正确设置
事件
以在不同的浏览器上工作。代码可以是:但我会像这样重写您的代码(未测试):
并从 HTML 中删除
onsubmit="formSubmit()"
。Do you want to stop the normal submission of a form when user hits Enter or clicks the submit button? Then you need to prevent the
event
from taking the default action. Try this:Edit: And as Trevor mentions, you should use jQuery to bind your function so that the
event
is properly setup to work across different browsers. The code could be:But I would rewrite your code like this (NOT tested):
And remove the
onsubmit="formSubmit()"
from your HTML.首先,
var self=这个;
应该是
其次,
您必须将表单绑定到 jQuery 事件模型中的提交操作才能访问 $(this)。
例:
还有,为什么要解绑呢?
Firstly,
var self=this;
Should be
Secondly,
You must bind the form to the submit action within the event model of jQuery in order to access $(this).
Example:
Also, why do you want to unbind it?