PHP/Javascript Checkbox to change form action when checked

Ash King picture Ash King · Apr 4, 2013 · Viewed 8.6k times · Source

This is what I got:

<form action="invoiceCreate.php" method="post">
<input type="checkbox" name="business" id="business" vaulue="yes" />

Basically when I check the "business" checkbox, I want the form action to change to BusinessInoiveCreate.php instead of InvoiceCreate.php.

What would be the best way to do so?

Answer

Chase picture Chase · Apr 4, 2013

Since it's not specified, here's a simple way to do it without jQuery. Depending on browser compatibility you may need to attach the event listener differently, but the general concept is the same.

HTML

<form name="myForm" action="invoiceCreate.php" method="post">
  <input type="checkbox" name="business" id="business" vaulue="yes" />
</form>

Javascript

var form = document.getElementsByName("myForm")[0];
var checkBox = document.getElementById("business");

checkBox.onchange = function(){
  if(this.checked){
    form.action = "giveEmTheBusiness.php";
  }else{
    form.action = "invoiceCreate.php";
  }
  console.log(form.action);
};

Or similarly, bind an event to the submit

form.onsubmit = function(){
  if(checkBox.checked)
      form.action = "giveEmTheBusiness.php"
  else
      form.action = "invoiceCreate.php";
};

EXAMPLE