使用JavaScript捕获表单提交

时间:2011-03-21 22:54:40

标签: javascript html forms

似乎有很多关于如何使用javascript提交表单的信息,但我正在寻找一种解决方案来捕获表单已经提交并在javascript中拦截它。

HTML

<form>
 <input type="text" name="in" value="some data" />
 <button type="submit">Go</button>
</form>

当用户按下提交按钮时,我希望提交表单,而是希望调用JavaScript函数。

function captureForm() {
 // do some stuff with the values in the form
 // stop form from being submitted
}

快速破解就是在按钮上添加一个onclick功能,但我不喜欢这个解决方案...提交表单有很多方法...例如在输入时按回车,这不考虑。

6 个答案:

答案 0 :(得分:75)

<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);
}

编辑:在我看来,这种方法比在表单上设置onSubmit属性更好,因为它保持了标记和功能的分离。但那只是我的两分钱。

Edit2 :更新了我的示例以包含preventDefault()

答案 1 :(得分:23)

在附加事件的元素已加载

之前,您无法附加事件

这有效 -

普通JS

DEMO

建议使用eventListener

window.addEventListener("load",function() {
  document.getElementById('my-form').addEventListener("submit",function(e) {
    e.preventDefault(); // before the code
    /* do what you want with the form */

    // Should be triggered on form submit
    alert('hi');
  });
});

但如果您不需要多个侦听器,则可以使用onload和onsubmit

// Should only be triggered on first page load
alert('ho');

window.onload=function() {
    document.getElementById('my-form').onsubmit=function() {
    /* do what you want with the form */

    // Should be triggered on form submit
    alert('hi');
    // You must return false to prevent the default form behavior
    return false;
  }
}

<强>的jQuery

// Should only be triggered on first page load
alert('ho');

$(function() {
  $('#my-form').on("submit",function(e) {
    e.preventDefault(); // cancel the actual submit

    /* do what you want with the form */

    // Should be triggered on form submit

    alert('hi');
  });
});

答案 2 :(得分:16)

<form onSubmit="return captureForm()"> 应该这样做。确保您的captureForm()方法返回false

答案 3 :(得分:5)

使用@Kristian Antonsen的回答,或者您可以使用:

$('button').click(function() {
    preventDefault();
    captureForm();
});

答案 4 :(得分:4)

处理我在练习中用于onload无法帮助的案例的所有请求的另一个选项是处理javascript提交,html提交,ajax请求。 这些代码应添加到body元素的顶部,以便在呈现和提交任何表单之前创建侦听器。

在示例中,我将隐藏字段设置为提交页面上的任何表单,即使它在页面加载之前发生。

//Handles jquery, dojo, etc. ajax requests
(function (send) {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    XMLHttpRequest.prototype.send = function (data) {
        if (isNotEmptyString(token) && isNotEmptyString(header)) {
            this.setRequestHeader(header, token);
        }
        send.call(this, data);
    };
})(XMLHttpRequest.prototype.send);


//Handles javascript submit
(function (submit) {
    HTMLFormElement.prototype.submit = function (data) {
        var token = $("meta[name='_csrf']").attr("content");
        var paramName = $("meta[name='_csrf_parameterName']").attr("content");
        $('<input>').attr({
            type: 'hidden',
            name: paramName,
            value: token
        }).appendTo(this);

        submit.call(this, data);
    };
})(HTMLFormElement.prototype.submit);


//Handles html submit
document.body.addEventListener('submit', function (event) {
    var token = $("meta[name='_csrf']").attr("content");
    var paramName = $("meta[name='_csrf_parameterName']").attr("content");
    $('<input>').attr({
        type: 'hidden',
        name: paramName,
        value: token
    }).appendTo(event.target);
}, false);

答案 5 :(得分:0)

使用 addEventListener 和 event.preventDefault 的替代方法是更改​​表单提交本身。这种方法看起来更健壮,尤其是在表单附加了其他事件侦听器的情况下。

我们可以使用以下代码更新表单提交:

form.originSubmit = form.submit
form.submit = function () {
  submitHandlerAsync(form)
  return false
}

在帖子中查看更多详细信息:https://runkiss.blogspot.com/2021/05/intercept-html-forms-submit.html