Home > Back-end >  How do I conditionally set a form action via Javascript?
How do I conditionally set a form action via Javascript?

Time:11-13

I'm trying to conditionally set the value of a form action attribute depending on whether a checkbox is ticked or not.

I have the following Javascript code:

function validate()
  {
    var f = document.getElementById("confirmForm");
    f.setAttribute('method',"post");
    if (document.getElementById('confirmOptionCompare').checked)
    {
      f.setAttribute('action',"comparison.php");
    } else {
      {
        f.setAttribute('action',"bookConfirm.php");
      }
    }
  }
  return true;
}

I'm including the above in my HTML document as follows:

<script type="text/javascript" src="code/scripts.js"></script>

I'm trying to trigger it as follows, but it doesn't navigate to the page I need it to navigate to:

<form id="confirmForm" onsubmit="return validate()">
  <p>Click confirm to go to the next step:</p>
  <button type="submit" name="confirm">Confirm</button>
</form>

The checkbox that should trigger the if is worded as follows (in a table):

 <tr>
          <td><?php echo $bookingOutput['name']." ".$bookingOutput['surname'];?></td>
          <td><?php echo $bookingOutput['email']; ?></td>
          <td><?php echo $bookingOutput['checkIn']." -> ".$bookingOutput['checkOut'];?></td>
          <td><?php echo $bookingOutput['daysStaying']; ?></td>
          <td><?php echo $bookingOutput['hotel'];?></td>
          <td><?php echo "R".$dailyRate ?></td>
          <td><?php echo $confirmationObj->ratePerDay; ?></td>
          <td><input type="checkbox" name="confirmOptionCompare" id="confirmOptionCompare"/>&nbsp;</td>
        </tr>

The checkbox is the final option above.

I'm not sure what I'm doing incorrect here. Any assistance would be greatly appreciated.

CodePudding user response:

Your code should work

In any case here is simpler version

document.getElementById("confirmForm").addEventListener("submit",function() {
  this.method="post"
  this.action = document.getElementById('confirmOptionCompare').checked ? "comparison.php": "bookConfirm.php";
})
<form id="confirmForm">
  <p>Click confirm to go to the next step:</p>
  <button type="submit" name="confirm">Confirm</button>
</form>

<input type="checkbox" name="confirmOptionCompare" id="confirmOptionCompare"/>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

That said - you can submit and do a redirect simply by setting the header in the PHP

if (isset($_POST["confirmOptionCompare"])) header("location: comparison.php");
die();
  • Related