Change Form Action and Method attributes

Jul 15th, 2007

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.

 

 

Possibly Related posts:

  1. Vineet
    May 26th, 2008 at 04:18 | #1

    This script is not compatible
    with ie. but woking fine with mozilla.

  2. Satya Prakash Karan
    May 26th, 2008 at 09:09 | #2

    but you have not posted the error.

  3. satyakaran
    March 4th, 2009 at 03:10 | #3

    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();

  4. noodles
    April 14th, 2009 at 15:18 | #4

    forget about IE, it sucks.

  5. October 4th, 2009 at 02:53 | #5

    Hello!

    I’d like to introduce you

    http://thesaltydroidnow.wordpress.com

    cheers!

Comments are closed.