拦截使用JavaScript提交的表单并阻止正常提交 [英] Intercept a form submit in JavaScript and prevent normal submission

查看:103
本文介绍了拦截使用JavaScript提交的表单并阻止正常提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于如何使用javascript提交表单似乎有很多信息,但是我正在寻找一种解决方案,以捕获表单提交后在javascript中进行拦截的方法.

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>

当用户按下提交"按钮时,我希望提交表单,但我希望调用JavaScript函数.

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
}

一个快速的技巧是在按钮上添加onclick函数,但我不喜欢这种解决方案...提交表单的方法有很多...例如在输入时按回车键,这不能说明问题.

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>

在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 :在我看来,这种方法比在表单上设置onSubmit属性更好,因为它保持了标记和功能的分离.但这只是我的两分钱.

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 :更新了我的示例以包括preventDefault()

Edit2: Updated my example to include preventDefault()

这篇关于拦截使用JavaScript提交的表单并阻止正常提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆