Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different form action according to different submit button

If I have a form which have 2 buttons , and when I click Button1 then it will be action="submit1.php" , if Button2 then action="submit2.php".

I tried this:

  <script language="javascript">

  function Button1()
   {
     document.Form1.action = "submit1.php"   
     document.Form1.target = "iframe1";    
     document.Form1.submit();        

   }

  function Button2()
   {
    document.Form1.action = "submit2.php" ;
    document.Form1.target = "iframe2";    
    document.Form1.submit();       
   }

 </script>

Somewhere in the <body>:

  <div style="visibility:hidden">
  <iframe NAME="iframe1" WIDTH="40" HEIGHT="40"></iframe>
  <iframe NAME="iframe2" WIDTH="40" HEIGHT="40"></iframe>
  </div>

And in the form:

  <form name="Form1" id="Form1" method="post">
  <input type="submit" name="Button1" onclick="Button1();">
  <input type="submit" name="Button2" onclick="Button2();">
  </form>

It's not working , am I make anything wrong?

Thank you.

like image 456
Irene Ling Avatar asked Jan 22 '26 01:01

Irene Ling


1 Answers

You have two issues

EITHER

change the buttons to type="button"

OR

remove the submit from the functions

Plain JS (using the simpler forms access):

<script language="javascript">
function Button(theButton) {
  var theForm = theButton.form;
  if (theButton.name=="Button1") {
    theForm.action = "submit1.php"   
    theForm.target = "iframe1";    
  }
  else {
    theForm.action = "submit2.php"   
    theForm.target = "iframe2";    
  }
}
</script>

<form method="post" action="nojsavailable.php">
  <input type="submit" name="Button1" onclick="Button(this);" />
  <input type="submit" name="Button2" onclick="Button(this);" />
</form>

Unobtrusively (recommended):

<script language="javascript">
window.onload=function() {
  var buttons = document.getElementsByName("button");
  for (var i=0;i<buttons.length;i++) {
    buttons[i].onclick=function() {
      var idx = i+1;
      var theForm = this.form;
      theForm.action = "submit"+idx+".php"   
      theForm.target = "iframe"+idx;    
    }
  }
}
</script>

<form method="post" action="nojsavailable.php">
  <input type="submit" name="button" id="button1" />
  <input type="submit" name="button" id="button2" />
</form>
like image 130
mplungjan Avatar answered Jan 25 '26 14:01

mplungjan