【问题标题】:How to submit form and redirect users to different pages based on what they have chooses in the drop down menu如何根据用户在下拉菜单中选择的内容提交表单并将用户重定向到不同的页面
【发布时间】:2017-08-17 15:26:47
【问题描述】:

我正在开发一个 html 页面,用户在该页面中提交一个表单,该表单包含一个下拉框以从中选择一个值。一旦用户提交表单,我想提交表单并根据他们在下拉框中选择的内容将用户重定向到不同的页面。

HTML 表单代码

<form action="#" method="post" class="form-group" id="dtls">
          <label for="sp">Choose one:</label><select name="sp" id="sponsor" class="form-control">
            <option value="mark" id="s1">Mark</option>
            <option value="markus" id="s2">Markus</option>
          </select>
          <label for="mail">Your Email:</label><input type="email" name="mail" class="form-control" placeholder="Email Address...">
          <input type="submit" name="sub" class="btn form-control btn-success" id="but">
        </form>

谁能建议我一个应对这一挑战的好方法? 谢谢

【问题讨论】:

  • 在 PHP 中(因为你已经标记了它),对表单值做任何你需要的事情,然后执行一些逻辑(基本的 ifswitch)并将它们重定向到相关页面.

标签: javascript php jquery forms onsubmit


【解决方案1】:

当然,在你的 JS 中是这样的:

redirectPage() {
  // Gets value of dropdown
  var selectedOption = $("#sponsor option:selected").val();

  // Picks correct url to go to
  var url;
  switch(selectedOption) {
    case "mark":
      url = "your link #1 here";
      break;
    case "markus":
      url = "your link #2 here";
      break;
    default:
      url = "";
      break;
  }

  // Changes current page and keeps back history
  window.location.assign(url);
}

摆脱大 switch 语句的简单方法是将每个选项的值作为 url,如果您没有将下拉值用于其他任何内容。您可以随时将.val() 替换为.text(),以从下拉列表中删除“Mark”和“Markus”。

参考资料:

Get the value of a dropdown in jQuery

How to redirect to another webpage in JavaScript/jQuery?

【讨论】:

    【解决方案2】:

    php

    if(isset($_POST["sub"])) {
        $value = $_POST["sp"];
        header("location: /$value");
    }
    

    您可以使用该值执行 if 语句,或者您可以像我一样设置标题或 echo javascript window.location 直接重定向用户

    jQuery

    $("#dtls").submit(function() {
        var value = $("#sponsor").val();
        if(value == "mark") {
            window.location.href = "/mark";
        } elseif(value == "markus") {
            window.location.href = "/markus";
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2014-08-05
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多