如何根据使用单个表单选择的单选按钮来修复将代码转到不同页面的代码 [英] How to fix the code to go for different pages according to radio button selected using single form

查看:189
本文介绍了如何根据使用单个表单选择的单选按钮来修复将代码转到不同页面的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转到不同的模板(页面),而不用从单个表单中选择任何内容(单选按钮).我只想在表单中包含一个按钮.

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.

在这里,好像有人选择了template1,我将转到template1.php. 如果选择template2,我将转到template2.php.

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

我将以下代码另存为form.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>

推荐答案

为此,请使用JavaScript. PHP是一种服务器端语言,这意味着您必须在PHP知道选择哪个选项之前将表单提交给服务器.当您更改此权限时,JavaScript可以处理此权限,因为它是一种客户端语言.

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.

创建一个事件侦听器,以单击名称为template的输入.然后相应地切换操作.

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>

这篇关于如何根据使用单个表单选择的单选按钮来修复将代码转到不同页面的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆