使用JavaScript捕获表单提交

mrw*_*ter 68 html javascript forms

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

HTML

<form>
 <input type="text" name="in" value="some data" />
 <button type="submit">Go</button>
</form>
Run Code Online (Sandbox Code Playgroud)

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

function captureForm() {
 // do some stuff with the values in the form
 // stop form from being submitted
}
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*nan 77

<form id="my-form">
    <input type="text" name="in" value="some data" />
    <button type="submit">Go</button>
</form>
Run Code Online (Sandbox Code Playgroud)

在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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 请注意,附件事件代码需要在dom中的表单可用后执行.例如,使用`window.onload = function(){...}`来包装它 (2认同)

mpl*_*jan 24

您附加的元素在加载之前无法附加事件

这工作 -

简单的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');
  });
});
Run Code Online (Sandbox Code Playgroud)

但如果您不需要多个侦听器,则可以使用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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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');
  });
});
Run Code Online (Sandbox Code Playgroud)

  • @ChrisMarisic - 几岁:)我已经更新了答案,包括jQuery (2认同)

kba*_*kba 16

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


Vit*_*sok 5

在 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);
Run Code Online (Sandbox Code Playgroud)