我怎样才能在javascript中听表单提交事件? [英] How can I listen to the form submit event in javascript?
问题描述
我想写我自己的表单验证JavaScript库,我一直在寻找谷歌如何检测是否点击提交按钮,但我发现的是代码,你必须使用点击 onSubmit = function()
in html。
我想制作这个javascript,以便我不必触摸任何html代码添加onSubmit或onClick javascript。
在jquery中,如果你有这样的表单:
< form id =hello-世界action =sayhello>
< input type =submitvalue =Hello!>
< / form>
您可以添加如下的事件处理程序:
$('#hello-world')。submit(function(ev){
ev.preventDefault(); //停止表单提交
/ *验证到这里* /
this.submit(); //如果所有验证成功
});
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.
Writing event handlers in vanilla javascript can be annoying to make work across browsers, so I'd recommend using a library like jquery to make it robust (and also easier to write).
In jquery, if you have a form like this:
<form id="hello-world" action="sayhello">
<input type="submit" value="Hello!">
</form>
You can attach an event handler like this:
$('#hello-world').submit(function(ev) {
ev.preventDefault(); // to stop the form from submitting
/* Validations go here */
this.submit(); // If all the validations succeeded
});
这篇关于我怎样才能在javascript中听表单提交事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!