dongpu9481 2019-05-08 07:45
浏览 152
已采纳

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

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>
  • 写回答

1条回答 默认 最新

  • duanfang2708 2019-05-08 07:52
    关注

    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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题