Friday 9 October 2015

How to switch the ‘action’ field in an HTML form dynamically

It is often required that you need to send the data in the same form to different server-side scripts depending one certain criteria. JavaScript allows you to modify the action field of an HTML form dynamically.
 

Multiple submit buttons

It is possible to have more than one submit button in a form. The example below shows how to switch the action field based on the submit button pressed.
 
<script type="text/javascript">
function OnSubmitForm()
{
  if(document.pressed == 'Insert')
  {
   document.myform.action ="insert.html";
  }
  else
  if(document.pressed == 'Update')
  {
    document.myform.action ="update.html";
  }
  return true;
}
</script>

<form name="myform" onsubmit="return onsubmitform();">
 
<input type="submit" name="operation" onclick="document.pressed=this.value" value="insert" />
 
<input type="submit" name="operation" onclick="document.pressed=this.value" value="update" />
 
</form>
 
 

Based on a radio button

The example below shows a case where the action field is switched based on the selection in the radio buttons.


<script type="text/javascript">
function OnSubmitForm()
{
  if(document.myform.operation[0].checked == true)
  {
    document.myform.action ="insert.html";
  }
  else
  if(document.myform.operation[1].checked == true)
  {
    document.myform.action ="update.html";
  }
  return true;
}
</script>
<form name="myform" onsubmit="return OnSubmitForm();">
   name: <input type="text" name="name"><br>
   email: <input type="text" name="email"><br>
   <input type="radio" name="operation" value="1" checked>insert
   <input type="radio" name="operation" value="2">update
   <p>
   <input type="submit" name="submit" value="save">
   </p>
</form>

No comments:

Post a Comment