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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失