Javascript 如何在javascript中收听表单提交事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7410063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:10:20  来源:igfitidea点击:

How can I listen to the form submit event in javascript?

javascriptformsvalidation

提问by ed1t

I wanna write my own form validation javascript library and I've been looking on google how to detect if a submit button is clicked but all I found is code where you have to use onClick on onSubmit="function()"in html.

我想编写自己的表单验证 javascript 库,我一直在 google 上寻找如何检测提交按钮是否被点击,但我发现的只是你必须onSubmit="function()"在 html 中使用 onClick on 的代码。

I would like to make this javascript so that I don't have to touch any html code like adding onSubmit or onClick javascript.

我想制作这个 javascript,这样我就不必接触任何 html 代码,比如添加 onSubmit 或 onClick javascript。

回答by u283863

Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?

为什么人们总是在不需要的时候使用 jQuery?
为什么人们不能只使用简单的 JavaScript?

var ele = /*Your Form Element*/;
if(ele.addEventListener){
    ele.addEventListener("submit", callback, false);  //Modern browsers
}else if(ele.attachEvent){
    ele.attachEvent('onsubmit', callback);            //Old IE
}

callbackis a function that you want to call when the form is being submitted.

callback是您要在提交表单时调用的函数。

About EventTarget.addEventListener, check out this documentation on MDN.

关于EventTarget.addEventListener,请查看MDN 上的此文档

To cancel the native submitevent (prevent the form from being submitted), use .preventDefault()in your callback function,

要取消本机submit事件(防止提交表单),请.preventDefault()在您的回调函数中使用,

document.querySelector("#myForm").addEventListener("submit", function(e){
    if(!isValid){
        e.preventDefault();    //stop form from submitting
    }
});


Listening to the submitevent with libraries

submit用图书馆收听事件

If for some reason that you've decided a library is necessary (you're already using one or you don't want to deal with cross-browser issues), here's a list of ways to listen to the submit event in common libraries:

如果由于某种原因您决定需要一个库(您已经在使用一个库或者您不想处理跨浏览器问题),以下是在公共库中侦听提交事件的方法列表:

  1. jQuery

    $(ele).submit(callback);
    

    Where eleis the form element reference, and callbackbeing the callback function reference. Reference

  1. jQuery

    $(ele).submit(callback);
    

    ele表单元素引用在哪里,是callback回调函数引用。参考

    <iframe width="100%" height="100%" src="http://jsfiddle.net/DerekL/wnbo1hq0/show" frameborder="0"></iframe>

  1. AngularJS (1.x)

    <form ng-submit="callback()">
    
    $scope.callback = function(){ /*...*/ };
    

    Very straightforward, where $scopeis the scope provided by the framework inside your controller. Reference

  2. React

    <form onSubmit={this.handleSubmit}>
    
    class YourComponent extends Component {
        // stuff
    
        handleSubmit(event) {
            // do whatever you need here
    
            // if you need to stop the submit event and 
            // perform/dispatch your own actions
            event.preventDefault();
        }
    
        // more stuff
    }
    

    Simply pass in a handler to the onSubmitprop. Reference

  3. Other frameworks/libraries

    Refer to the documentation of your framework.

  1. AngularJS (1.x)

    <form ng-submit="callback()">
    
    $scope.callback = function(){ /*...*/ };
    

    非常简单,控制器$scope内部框架提供的范围在哪里。参考

  2. 反应

    <form onSubmit={this.handleSubmit}>
    
    class YourComponent extends Component {
        // stuff
    
        handleSubmit(event) {
            // do whatever you need here
    
            // if you need to stop the submit event and 
            // perform/dispatch your own actions
            event.preventDefault();
        }
    
        // more stuff
    }
    

    只需将处理程序传递给onSubmit道具。参考

  3. 其他框架/库

    请参阅您的框架的文档。



Validation

验证

You can always do your validation in JavaScript, but with HTML5 we also have native validation.

您始终可以使用 JavaScript 进行验证,但使用 HTML5 我们也可以进行本机验证。

<!-- Must be a 5 digit number -->
<input type="number" required pattern="\d{5}">

You don't even need any JavaScript! Whenever native validation is not supported, you can fallback to a JavaScript validator.

你甚至不需要任何 JavaScript!每当不支持本机验证时,您可以回退到 JavaScript 验证器。

Demo: http://jsfiddle.net/DerekL/L23wmo1L/

演示:http: //jsfiddle.net/DerekL/L23wmo1L/

回答by Derek Dawson

This is the simplest way you can have your own javascript function be called when an onSubmitoccurs.

这是您可以在onSubmit发生时调用自己的 javascript 函数的最简单方法。

HTML

HTML

<form>
    <input type="text" name="name">
    <input type="submit" name="submit">
</form>

JavaScript

JavaScript

window.onload = function() {
    var form = document.querySelector("form");
    form.onsubmit = submitted.bind(form);
}

function submitted(event) {
    event.preventDefault();
}

回答by HEDWIN

Based on your requirements you can also do the following without libraries like jQuery:

根据您的要求,您还可以在没有 jQuery 等库的情况下执行以下操作:

Add this to your head:

将此添加到您的头上:

window.onload = function () {
    document.getElementById("frmSubmit").onsubmit = function onSubmit(form) {
        var isValid = true;
        //validate your elems here
        isValid = false;

        if (!isValid) {
            alert("Please check your fields!");
            return false;
        }
        else {
            //you are good to go
            return true;
        }
    }
}

And your form may still look something like:

您的表单可能仍然如下所示:

    <form id="frmSubmit" action="/Submit">
        <input type="submit" value="Submit" />
    </form>

回答by Justin808

With jQuery:

使用 jQuery:

$('form').submit(function () {
    // Validate here

    if (pass)
        return true;
    else
        return false;
});