Javascript/jQuery-基于下拉选择转到URL

Javascript / jQuery - Goto URL based on Drop Down Selections

本文关键字:URL 选择 于下拉 jQuery- Javascript      更新时间:2023-09-26

我有3个下拉框和一个go按钮。我需要转到一个基于在3个URL框中选择的内容构建的URL——这里是我的代码示例。

  <form>
  <select class="dropdown" id="dd1" style="margin-right:10px;width:130px">
    <option>http://</option>
    <option>ftp://</option>
    <option>https://</option>
  </select>
  <select class="dropdown" id="dd2" style="margin-right:10px;width:130px">
    <option>google</option>
    <option>yahoo</option>
    <option>bbc</option>
    <option>hotmail</option>
  </select>
  <select class="dropdown" id="dd3" style="width:130px;margin-right:20px">
    <option>.com</option>
    <option>.net</option>
    <option>.co.uk</option>
  </select>
  <input type="submit" name="button" id="button" value="Go!">
  </form>

因此,例如,如果用户选择http://+yahoo+.net,然后点击"Go"按钮,他们将被发送到http://yahoo.net或者,如果用户选择https://+hotmail+.com,则会将其发送到https://hotmail.com

是否有一些jQuery或Javascript代码可以检测下拉列表中的选择,然后构建正确的URL,并在按下"Go"按钮时转到它?

谢谢Zach

类似的东西?

window.location.href = $('#Dropwdown_1').val()+$('#Dropwdown_2').val()+$('#Dropwdown_3').val();

获取下拉的值

var searcher = document.getElementById("ddlSearch");
var searchDomain =searcher.options[searcher.selectedIndex].text;

其他两个相同

然后使用+连接字符串

var url = searchProtocol + searchDomain + searchTopLevel;

进入页面:

location.href= url;

@zach

这应该很简单。

  • 使用Select HTML标记并为3个下拉菜单指定选项
  • 在JS中创建一个函数createURL()
  • 获取三个框的值。您可以使用document.getElementById('Select1').options[document.getElementById('Select 1').selectedIndex].value并使用加号进行连接
  • 您也可以使用JQuery,这将使工作更简单
  • 您可以使用window.location.htm在同一页面中打开
var d1 = $("#dd1").find(":selected").attr("value");
var d2 = $("#dd2").find(":selected").attr("value");
var d3 = $("#dd3").find(":selected").attr("value");
location.href = d1+d2+d3+"";

当其他答案有效时。。。我更喜欢用这种方式处理它(使用jQuery):

$("form").on("submit", function(e) {
    // Define our global url array
    var url = [];
    // Prevent the form from processing
    e.preventDefault();
    // Loop through the drop down fields, storing the value of each into our "url" array
    $(this).find(".dropdown").each(function() {
        url.push($(this).val());
    });
    // Change the page location
    window.location = url.join("");
});