以编程方式提交表格之前 [英] Before submitting form programmatically
问题描述
在jQuery-Mobile中,我以编程方式提交表单,并且我想捕获Submit事件以执行一些验证.我已经尝试过其他有关jQuery的问题中提供的以下解决方案:
In jQuery-Mobile I'm submitting a form programmatically and I want to capture the submit event to perform some validations before. I have already tried the following solution provided in other questions about jQuery:
$(document).ready(function(){
$('#my_form').bind('submit', function() {
alert('before submit');
...
});
});
但是我无法执行该功能并显示警报.有人知道实现此目标的其他方法吗?
But I cannot get the function executed and the alert displayed. Does anyone know any other way to achieve this?
我的表单类似于:
<form id="my_form" method="POST" action="..." data-theme="b">
在同一页的另一部分中,我以编程方式调用它的方式是这样的:
And the way I am calling it programmatically, from another section of the same page is like this:
<input type="submit" onclick="document.forms['my_form'].submit(); return false;" value="Submit" data-theme="b"/>
预先感谢您的帮助.
推荐答案
以编程方式提交表单时,不执行表单的提交处理程序.
The submit handler of the form is NOT executed when you submit the form programatically.
注意:请勿使用提交按钮以编程方式提交表单.而是使用按钮或允许处理来自提交按钮的提交,即
NOTE: Do NOT use a submit button to programatically submit a form. Instead use button or allow the submission from the submit button to be handled, i.e.
<input type="button" onclick="document.forms['my_form'].submit()" value="Submit another form" data-theme="b"/>
(以上内容仍然是不正确的,因为它需要表单具有名称,而不仅仅是ID)
(the above is not correct anyway since it needs the form to have a NAME, not just an ID)
所以
<input type="button" onclick="document.forms['my_form_NAME'].submit()" value="Submit another form" data-theme="b"/>
OR
<input type="button" onclick="document.getElementById('my_form_ID').submit()" value="Submit another form" data-theme="b"/>
或者因为您拥有jQuery:
OR since you have jQuery:
<input type="button" onclick="$('#my_form_ID'].submit()" value="Submit another form" data-theme="b"/>
或者,如果您可以将按钮放入表单(最佳方式):
OR if you can put the button in the form (best way):
<input type="submit" value="Submit THIS form" data-theme="b"/>
但是,由于您要绑定-这是使用其他按钮提交而不是使用表单自己的提交按钮的更好方法的方法:
But since you want to bind - here is how to submit using another button instead of the better way using the form's own submit button:
<form id="actualForm">...
.
.
</form>
<input type="button" id="subbut" value="Submit another form on this page" data-theme="b"/>
$(document).ready(function(){
$('#subbut').bind('click', function() {
alert('before submit');
...
$("#actualForm").submit();
});
});
如果您无法更改硬编码的内联行为,也可以使用jQuery将其删除
If there is hardcoded inline behaviour you cannot change, use the jQuery to remove it too
$(document).ready(function(){
$('#subbut').attr('onclick',""); // or $('#subbut').onclick=null;
$('#subbut').bind('click', function() {
alert('before submit');
...
$("#actualForm").submit();
});
});
这篇关于以编程方式提交表格之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!