【问题标题】:populate first option of dropdown with URL parameter使用 URL 参数填充下拉列表的第一个选项
【发布时间】:2021-03-10 15:03:59
【问题描述】:

我正在尝试根据提供的 URL 参数设置下拉选择的第一个选项。

我正在使用以下代码获取 URL 参数:

var getUrlParameter = function getUrlParameter(sParam) {
  var sPageURL = window.location.search.substring(1),
    sURLVariables = sPageURL.split('&'),
    sParameterName,
    i;

  for (i = 0; i < sURLVariables.length; i++) {
    sParameterName = sURLVariables[i].split('=');

    if (sParameterName[0] === sParam) {
      return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
    }
  }
  return false;
};

网址可能如下所示:

https://development.mycompany.com/project/home.php?profile=profile1,profle2&region=&rep=JOHN%20BEASLEY

然后我可以调用 getUrlParameter() 函数来获取 rep 参数:

var rep = getUrlParameter('rep');

console.log(rep);

$('#rep').val(rep); // <-- my attempt to set the first option of the dropdown

我可以在控制台中看到 rep 变量。但是,当尝试设置下拉选择的第一个选项时,它仍然是空白的。

这是下拉菜单:

<select class="form-control rep" id="rep"></select>    

我应该能够在下拉菜单中看到“JOHN BEASLEY”作为选定选项。

下拉列表包含“JOHN BEASLEY”以及其他代表,但它应该显示为最初选择的样子。我很困惑为什么这不起作用。

我做错了什么,我该如何解决?

*** 编辑 ***

我最初使用以下函数填充下拉列表:

function initializeSelect($select, uri, adapt){     
$.getJSON( uri, function( data ) {
    $select.empty().append($('<option>'));      
    $.each(data, function(index, item) {
        var model = adapt(item);
        var $option = $('<option>');
        $option.get(0).selected = model.selected;
        $option.attr('value', model.value)
            .text(model.text)
            .appendTo($select);                     
    });
});
};

然后我像这样填充下拉列表:

initializeSelect($('#rep'), 'api/getReps.php', function (item){ 
return {
    value: item.fullname,
    text: item.fullname,
    style: 'color:black'
}
}); 

使用上述方法,下拉列表成功填充了我的 dB 表中的所有选项。

JOHN BEASLEY 选项在下拉列表中可用。

【问题讨论】:

  • &lt;select&gt; 显示为空?您是在尝试创建这样的 &lt;option&gt;,还是已经存在具有该值的 &lt;option&gt;
  • 该选项已存在于下拉菜单中。我正在尝试获取下拉菜单以将所选选项显示为 URL 中的参数。
  • 那么请按照minimal reproducible example 提供&lt;option&gt; html。另一种可能性是您正在运行&lt;select&gt; 存在之前显示的代码
  • @charlietfl - 我更新了我的问题以包含最初填充下拉列表的函数。

标签: javascript jquery url parameters dropdown


【解决方案1】:

也许你可以只在 select 初始化后才设置 select.value,像这样:

function initializeSelect($select, uri, adapt){     
    $.getJSON( uri, function( data ) {
        $select.empty().append($('<option>'));      
        $.each(data, function(index, item) {
            var model = adapt(item);
            var $option = $('<option>');
            $option.get(0).selected = model.selected;
            $option.attr('value', model.value)
                .text(model.text)
                .appendTo($select);                     
        });
        $select.val(getUrlParameter('rep'));
    });
};

【讨论】:

  • 是的!那行得通!谢谢你,先生。我很感激。
猜你喜欢
  • 1970-01-01
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多