关于如何在表单上使用great answer here拦截提交,有一个addEventListener。只要表单是通过提交按钮(或输入)提交的,它就会工作得很好。
但是,当像这样被解雇的时候,它完全被忽略了:
document.getElementById('myform').submit();你会如何拦截这样的电话?
下面是一个例子:
<script>
function checkRegistration(){
var form_valid = (document.getElementById('some_input').value == 'google');
if(!form_valid){
alert('Given data is incorrect');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()" method="get" action="http://google.com" id='myform'>
Write google to go to google..<br/>
<input type="text" id="some_input" value=""/>
<input type="submit" value="google it"/>
</form>
<a href="javascript:document.getElementById('myform').submit();">Ignore validation</a>发布于 2018-02-15 18:39:12
好的。这里有一个可能的解决方案,它需要一些锤击,但可能有效:
这是你的样本:
<script>
function checkRegistration(){
var form_valid = (document.getElementById('some_input').value == 'google');
if(!form_valid){
alert('Given data is incorrect');
return false;
}
return true;
}
</script>html:
<form onsubmit="return checkRegistration()" method="get" action="http://google.com" id='myform'>
Write google to go to google..<br/>
<input type="text" id="some_input" value=""/>
<input type="submit" value="google it"/>
</form>
<a href="javascript:document.getElementById('myform').submit();">Ignore validation</a>这是一个开始捕捉事件的算法。与其覆盖onsubmit事件(如果您调用form.submit编程器,它似乎会被忽略),您必须重写表单的submit方法。
<script>
//document.getElementById('myform').onsubmit = function() {alert('testing'); return false;}
var form = document.getElementById('myform');
// Store the original method
var tmp = form.submit;
// create an intercept and override the submit method for the form with it
form.submit = function(){
var form_valid = (document.getElementById('some_input').value == 'google');
if(!form_valid){
alert('Given data is incorrect');
return false;
}
// when happy with the validation, apply the old method to the form
tmp.apply(form);
}
</script>我在本地的机器上试了一下,看起来很管用。现在,您必须将该算法推广到处理任意形式。这也许能解决你的问题。
发布于 2018-02-15 17:28:20
事件侦听器只在user action submits the form发生时才触发。
document.getElementById('myform').addEventListener(
"submit",
function(e){
e.preventDefault();
console.log("not submitting form");
}
);
//the following never triggers the event listener:
//https://stackoverflow.com/questions/645555/should-jquerys-form-submit-not-trigger-onsubmit-within-the-form-tag
//document.getElementById('myform').submit();<form id="myform">
<input type="submit" >
</form>
解决办法可以是:
if(validation){
myForm.submit();
}发布于 2018-02-15 17:37:54
我想我刚找到你要找的东西了。您应该直接设置操作,让JS在提交时处理它。
function check(){
var form_valid = (document.getElementById('some_input').value == 'google');
if(!form_valid){
alert('Given data is incorrect');
return false;
}
return true;
}<form id="myform" action="javascript:check();">
<input type="text" id="some_input">
<input type="submit">
</form>你也可以这样做:
<form ... action="javascript:function(){...}">
https://stackoverflow.com/questions/48811789
复制相似问题