JavaScript动态更改表单提交事件

6

我有一个表单,其中包含一些操作和onsubmit值,可以通过提交输入标签进行提交。问题在于它应该可通过两个按钮进行提交,因此我编写了一个函数来更改表单的操作和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;
}

点击“比较”链接后,页面正确地跳转到anotherAction.php页面,但即使我选择了两个以上的复选框(这是验证规则),表单仍然可以被提交。请问是否有人能帮我使onsubmit函数正常工作?


只是一点小建议,我认为(n > 2)就足够了,而不必写成(n >= 3) - codingbiz
3个回答

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

应该是

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

在提交时返回false将只结束任何进一步的函数执行。如果您不想提交,您需要preventDefault提交行为。


尝试过了,但提交流程的行为没有任何变化。 - user1507558
也许是你的 countChecked 函数有问题。尝试使用 console.log 查看它是否正确获取了选中复选框的数量。 - Trevor
countChecked() 函数返回了正确的值。我真的不知道为什么你的解决方案不起作用,但 @Otto Allmendinger 给出了一个正确的答案,所以问题已经解决 :) - user1507558

4
这是一份晚回复,但如果有其他人正在查看这个问题...
可以改为:
虽然回复晚了,但如果还有其他人关注这个问题...
document.myForm.onsubmit = function() {return countChecked()};

我想您需要的是:

我认为您需要:

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

你节省了我宝贵的最后一分钟时间。 - FatherMathew

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


 document.myForm.submit();

你可能想要的是

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

非常感谢!这样简化了整个概念,而且真的有效果! - user1507558

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接