在JavaScript中捕获表单提交 [英] Capture a form submit in JavaScript
问题描述
似乎有很多关于如何使用javascript提交表单的信息,但是我正在寻找一种解决方案来捕获表单提交并在javascript中拦截它。
HTML
< form>
< input type =textname =invalue =some data/>
< button type =submit> Go< / button>
< / form>
当用户按下提交按钮时,我会不是希望表单()函数captureForm(){
/
$ $ $ $ $ $ $ $ $ $ $ $ $ $' /以
形式的值做一些事情//停止表单提交
}
一个简单的黑客可能会在按钮上添加一个onclick函数,但我不喜欢这个解决方案......有许多方法可以提交表单...例如在输入时按下回车键,这并不占用。
Ty
< form id =my-form>
< input type =textname =invalue =some data/>
< button type =submit> Go< / button>
< / form>
在JS中:
函数processForm(e){
if(e.preventDefault)e.preventDefault();
* *按照表格* /
来做你想做的事情//你必须返回false来防止默认的表单行为
return false;
}
var form = document.getElementById('my-form');
if(form.attachEvent){
form.attachEvent(submit,processForm);
} else {
form.addEventListener(submit,processForm);
}
编辑:在我看来,这种方法是比在表单上设置 onSubmit
属性更好,因为它保持了标记和功能的分离。但这只是我的两分钱。
Edit2 :更新我的示例以包含 preventDefault()
There seems to be lots of info on how to submit a form using javascript, but I am looking for a solution to capture when a form has been submitted and intercept it in javascript.
HTML
<form>
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
When a user presses the submit button, I do not want the form to be submitted, but instead I would like a JavaScript function to be called.
function captureForm() {
// do some stuff with the values in the form
// stop form from being submitted
}
A quick hack would be to add an onclick function to the button but I do not like this solution... there are many ways to submit a form... e.g. pressing return while on an input, which this does not account for.
Ty
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
In JS:
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
// You must return false to prevent the default form behavior
return false;
}
var form = document.getElementById('my-form');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
Edit: in my opinion, this approach is better than setting the onSubmit
attribute on the form since it maintains separation of mark-up and functionality. But that's just my two cents.
Edit2: Updated my example to include preventDefault()
这篇关于在JavaScript中捕获表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!