javascript change form onsubmit dynamically
Asked Answered
C

3

6

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:

<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?

Champlin answered 6/7, 2012 at 18:48 Comment(1)
Just a side-note, I think (n > 2) is enough instead of (n >= 3)Minatory
S
1

In submitCompare(), you explicitly and unconditionally call

 document.myForm.submit();

What you probably want instead there is

 if (countChecked()) {
   document.myForm.submit();
 }
Steinway answered 6/7, 2012 at 18:53 Comment(1)
Thanks a lot, that way it simplifies the whole idea and actually works!Champlin
O
7
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.

Overriding answered 6/7, 2012 at 18:52 Comment(3)
Tried it, but there was no change in the behaviour of the submit process.Champlin
Perhaps it is your countChecked function. try doing some console.log to see if it is getting the right amount of checked checkboxesOverriding
countChecked() returned correct values. I really don't know why your solution didn't work but @Otto Allmendinger got it right for me, so case closed :)Champlin
S
4

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()");
Stevenson answered 9/8, 2014 at 14:42 Comment(1)
You saved my valuable last minute timeFaden
S
1

In submitCompare(), you explicitly and unconditionally call

 document.myForm.submit();

What you probably want instead there is

 if (countChecked()) {
   document.myForm.submit();
 }
Steinway answered 6/7, 2012 at 18:53 Comment(1)
Thanks a lot, that way it simplifies the whole idea and actually works!Champlin

© 2022 - 2024 — McMap. All rights reserved.