如何根据使用单一表单选择的单选按钮修复代码以转到不同的页面

如何根据使用单一表单选择的单选按钮修复代码以转到不同的页面

问题描述:

I want to go to different templates(page) whatever is selected(radio button) from a single form. I want to include just one button in my form.

Here as if someone selects template1 I will to page template1.php. If I select template2 I will go to template2.php.

I have saved the below code as form.php

<form method="POST" action=
                          "<?php if(($rb = $_POST('template'))=='1'){?>
                                          template1.php 
                           <?php } 
                            if(($rb = $_POST('template'))=='2'){?>
                                          template2.php 
                            <?php } ?>"
                            enctype="multipart/form-data"> 
         <label>First Name: </label>
         <input type="text" name="firstname">
         <label>Last Name: </label>
         <input type="text" name="lastname">
         <input type="radio" value="1" name="template">Template 1
         <input type="radio" value="2" name="template">Template 2
         <button type="submit" name="upload">POST</button>      

  </form>

Use JavaScript for this instead. PHP is a server-side language, which means that you have to submit the form to the server before PHP knows which option you selected. JavaScript can deal with this right when you change it instead, as it is a client-side language.

Create an event-listener for a click on the input with the name of template. Then toggle the action accordingly to that.

$("input[name=template]").on("click", function() {
  var action = "";
  switch($(this).val()) {
    case "1":
      action = 'template1.php';
      break;
    case "2":
      action = 'template2.php';
      break;
  }
  $(this).parent("form").prop("action", action);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" action="" enctype="multipart/form-data"> 
         <label>First Name: </label>
         <input type="text" name="firstname">
         <label>Last Name: </label>
         <input type="text" name="lastname">
         <input type="radio" value="1" name="template">Template 1
         <input type="radio" value="2" name="template">Template 2
         <button type="submit" name="upload">POST</button>      

  </form>

</div>