Javascript change onsubmit form dynamically

I have a form with some onsubmit actions and values ​​that are passed through an input tag. The problem is that it must be served by two buttons, so I wrote a function for the second button to change the action and onsubmit values ​​of the form:

<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 you click the “Compare” link, it will correctly send me to anotherAction.php page, but even if I have more than 2 selected checkboxes (this is a validation rule). Can someone help me make onsubmit work correctly?

+5
source share
3 answers

As submitCompare()you clearly and unequivocally call

 document.myForm.submit();

Instead, you might want to

 if (countChecked()) {
   document.myForm.submit();
 }
+1
document.myForm.onsubmit = function() {return countChecked()};

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

false submit . Default, .

+4

This is a late answer, but if someone looks at it ...

instead:

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

I think you would like:

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

All Articles