javascript javascript动态更改表单提交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11368000/
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-10-26 12:56:19  来源:igfitidea点击:

javascript change form onsubmit dynamically

javascriptvalidationcheckboxcheckedonsubmit

提问by user1507558

I have a form with some action and onsubmit values, which is submitted through a submit input tag. The problem is that it should be submittable by two buttons, so I wrote a function for the second button to change the action and onsubmit values of the form:

我有一个带有一些 action 和 onsubmit 值的表单,它是通过提交输入标签提交的。问题是它应该可以通过两个按钮提交,所以我为第二个按钮编写了一个函数来更改表单的 action 和 onsubmit 值:

<a href="javascript:submitCompare()" class="submit">Compare</a>

function submitCompare()
{
    document.myForm.action = "anotherAction.php";
    document.myForm.onsubmit = function() {return countChecked()};
    document.myForm.submit();
}

function countChecked()
{
  var n = $(".reports input:checked").length;
  if (n >= 3 ) {
    alert ('You must select less than 3 reports.');
    return false;
  }
  else return true;
}

After clicking on the Compare link it sends me to the anotherAction.php page correctly, but even when I have more than 2 selected checkboxes (which is the validation rule). Can somebody help me make the onsubmit function work correctly?

单击“比较”链接后,它会将我正确发送到 anotherAction.php 页面,但即使我选择了 2 个以上的复选框(这是验证规则)。有人可以帮助我使 onsubmit 功能正常工作吗?

采纳答案by Otto Allmendinger

In submitCompare(), you explicitly and unconditionally call

在 中submitCompare(),您明确且无条件地调用

 document.myForm.submit();

What you probably want instead there is

你可能想要的是

 if (countChecked()) {
   document.myForm.submit();
 }

回答by Trevor

document.myForm.onsubmit = function() {return countChecked()};

should be

应该

document.myForm.onsubmit = function( e ) {
   e = e || window.event;
   if ( !countChecked() ) {
       e.preventDefault();
       e.returnValue = false;
   }
};

Returning false on a submit will just end any further function execution. You want to preventDefault submission behavior if you don't want it to submit.

在提交时返回 false 只会结束任何进一步的函数执行。如果您不希望它提交,您希望阻止默认提交行为。

回答by Vlad

It is a late reply, but if someone else is looking at this...

这是一个迟到的回复,但如果其他人正在看这个......

instead of:

代替:

document.myForm.onsubmit = function() {return countChecked()};

I think you wanted:

我想你想要:

document.myForm.setAttribute("onsubmit", "return countChecked()");