简体   繁体   English

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

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

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库,我一直在看谷歌如何检测是否点击了提交按钮,但我发现的只是你必须在html中使用onClick onSubmit="function()"的代码。

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。

Why do people always use jQuery when it isn't necessary?为什么人们总是在不需要的时候使用 jQuery?
Why can't people just use simple JavaScript?为什么人们不能只使用简单的 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
}

callback is 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 submit event (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 submit event 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 jQuery

     $(ele).submit(callback);

    Where ele is the form element reference, and callback being the callback function reference.其中ele是表单元素引用,而callback是回调函数引用。 Reference参考

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

  1. AngularJS (1.x) AngularJS (1.x)

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

    Very straightforward, where $scope is the scope provided by the framework inside your controller .非常简单,其中$scope是您的控制器内部框架提供的范围。 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 onSubmit prop.只需将处理程序传递给onSubmit道具。 Reference参考

  3. Other frameworks/libraries其他框架/库

    Refer to the documentation of your framework.请参阅您的框架的文档。


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!你甚至不需要任何 JavaScript! Whenever native validation is not supported, you can fallback to a JavaScript validator.只要不支持本机验证,您就可以回退到 JavaScript 验证器。

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

See Derek's answer , which should now be the accepted answer. 请参阅Derek的答案 ,现在应该是接受的答案。 It includes everything this answer had included and more. 它包括这个答案所包含的一切以及更多。

(I tried to delete this answer after Derek updated his to include library examples, but with the green checkmark, SO won't let me) (我试图删除这个答案后Derek更新他的包含库示例,但有绿色选中标记,SO不会让我)

This is the simplest way you can have your own javascript function be called when an onSubmit occurs.这是在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();
}

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>

If you have multiple forms in same page & you wants to handle submit event Listener without using Id如果您在同一页面中有多个表单并且您想在不使用 Id 的情况下提交事件侦听器

jQuery jQuery

$('form').submit(function (event) {
    targetObj = event.target;
    // do your logic
});

Pure JavaScript trick纯 JavaScript 技巧

Onload just do below way. Onload只需按照以下方式进行。

for(var i=0; i<document.forms.length; i++){
    var form = document.forms[i];
    form.addEventListener("submit", myListener,false);
}

credit :- Multiple Form Submit Event Listener Handling using JavaScript credit goes to Jan Pfeifer's Answer on StackOverflow Community信用:- 使用 JavaScript 处理多表单提交事件侦听器信用转至Jan Pfeifer 在 StackOverflow 社区上的回答

I hope this helps to someone我希望这对某人有帮助

With jQuery:使用 jQuery:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM