如何在JavaScript中收听表格提交事件?

发布于 2025-02-13 23:25:31 字数 214 浏览 0 评论 0 原文

我想编写自己的表单验证JavaScript库,并且我一直在寻找Google如何检测是否单击提交按钮,但我发现的只是您必须在其中使用onclick On onsubmit =“ function()” < /代码>在HTML中。

我想制作此JavaScript,这样我就不必触摸任何HTML代码,例如添加OnSubmit或OnClick 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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

糖粟与秋泊 2025-02-20 23:25:31

为什么人们在不需要时总是使用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
}

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

关于 eventTarget.AddeventListener ,查看

要取消本机提交事件(防止表格被提交),请使用 .preventdefault() 在您的回调功能中,

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

收听提交带有库的事件,

如果由于某种原因决定了一个库(您已经在使用一个库,或者您不想处理跨浏览器问题)在普通库中收听提交事件的方法:

  1. jQuery

      $(ele).submit(呼叫);
     

    其中 ele 是表单元素参考, callback 是回调函数参考。 参考

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

  1. angularjs(1.x)

     &lt; form ng-submit =“ callback()”&gt;
    
    $ scope.callback = function(){/*....*/};
     

    非常简单,其中 $ scope “ noreferrer”>控制器参考

  2. eack

     &lt; form onSubmit = {this.handlesubmit}&gt;
    
    类YourComponent扩展了组件{
        // 东西
    
        handlesubmit(event){
            //在这里做任何您需要的事情
    
            //如果您需要停止提交事件,并且 
            //执行/派遣您自己的动作
            event.preventDefault();
        }
    
        //更多东西
    }
     

    只需将处理程序传递到 onsubmit prop。 参考

  3. 其他框架/libraries

    请参阅您的框架文档。


验证

您可以随时在JavaScript中进行验证,但是使用HTML5,我们也具有本机验证。

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

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

演示:

Why do people always use jQuery when it isn't necessary?
Why can't people just use simple 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.

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

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

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

Listening to the submit event with libraries

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 ele is the form element reference, and callback being the callback function reference. Reference

    <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 $scope is 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 onSubmit prop. 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.

<!-- 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.

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

初见终念 2025-02-20 23:25:31

这是当发生 OnSubmit 时,可以使用自己的JavaScript函数的最简单方法。

html

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

javaScript

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

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

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

HTML

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

JavaScript

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

function submitted(event) {
    event.preventDefault();
}
最舍不得你 2025-02-20 23:25:31

根据您的要求,您也可以在没有诸如jQuery之类的图书馆的情况下进行以下操作:

将其添加到您的头上:

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

您的表格可能仍然看起来像:

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

Based on your requirements you can also do the following without libraries like 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>
秋心╮凉 2025-02-20 23:25:31

如果您在同一页面中有多个表格&amp;您想处理提交事件听众而不使用ID

jQuery

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

纯JavaScript Trick

onload在下面的下载。

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

信用: - 多表单提交活动听众使用JavaScript信用来访问 Jan Pfeifer在Stackoverflow社区上的答案

我希望这对某人有帮助

If you have multiple forms in same page & you wants to handle submit event Listener without using Id

jQuery

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

Pure JavaScript trick

Onload just do below way.

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

I hope this helps to someone

著墨染雨君画夕 2025-02-20 23:25:31

与jQuery:

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

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

With jQuery:

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

    if (pass)
        return true;
    else
        return false;
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文