Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript change form onsubmit dynamically

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?

like image 540
user1507558 Avatar asked Jul 06 '12 18:07

user1507558


2 Answers

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.

like image 54
Trevor Avatar answered Sep 16 '22 19:09

Trevor


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()");
like image 30
Vlad Avatar answered Sep 19 '22 19:09

Vlad