Change Form Action and Method attributes

In case you want your form action value changed based on certain condition then you can do this using simple JavaScript. In this way you can submit your single form to any of your scripts based on condition.
Here you will also find tricks for changing the method attribute of the form using JavaScript.

<script type="text/javascript">
function changeAction (frm) {   // result after your conclusion
     var variable1 = 5;
// check condition based on which you decide action script
 if (variable1 > 6) {
     frm.action = 'test1.php?x=2';
     frm.submit(); return;
}
else {
     frm.action = 'test2.html';
     frm.submit();
     return;
}
   // change form method if you wish. you can make it conditional also.
  //frm.method = 'get';
   // if condition do not satisfy then do not submit it.
  return false;
}
</script>
<form name="frm1" action="test3.php" method="post" onsubmit="return changeAction(this);">
<input type="text" name="txtBox1" value="" />
<input type="submit" name="submit1" value="Submit" />
</form>

See here normally your form will be submitted to test3.php page. But it will go to test1.php or test2.html. In test1.php you will get x=2 in $_GET also. See the example there you can change the method to get also. Currently it is set to post.

  • # 1 - by satyakaran

    Some reported that it is not working in IE.I also tested in IE 7 and it was not working. comment this line there: //frm.submit();

  • # 2 - by noodles

    forget about IE, it sucks.

  • # 3 - by noodles

    forget about IE, it sucks.

Comment pages
1 2 230
Comments are open for an year period. Please, write here on Facebook page.