首页 > 解决方案 > 对下拉列表进行排序会更改所选选项

问题描述

我正在使用 HTML、Javascript、JQuery 创建一个 Web 应用程序,它不断从数据库中获取新数据并显示实时仪表板。我想遍历数据中名为“Group”的特定列,获取所有唯一值,然后使用排序的唯一“Group”值重新填充下拉列表。但是,在获取新数据之前,已经在下拉列表中选择了一个选项,例如 Group 02。我不希望仪表板切换到另一个组。只有当用户选择新组时,仪表板才会切换到该组。为了讨论起见,假设有两个组,“第 1 组”,“第 2 组”。

这就是我现在的做法:

let uniqueGroups =[...new Set(d.map(l => `<option>${l.Group}</option>`))];
    let grpCollator = new Intl.Collator(undefined, {sensitivity: 'base'});
    uniqueGroups.forEach(element=>{
      if (element.includes('undefined')){
        element = element.replace("undefined", "No Group Assigned");
      }
      if(this.allGroups.includes(element)==false) this.allGroups.push(element)
    })

    //#groupSelection is the id of the dropdown list
    $('#groupSelection').html(this.allGroups.sort(grpCollator.compare));

这段代码的问题是它会不断地将我的下拉列表中的选定选项切换到第 1 组(这是排序后的第一个选项)。因此,即使用户选择了第 2 组,此代码(应该只排序)也会排序并选择第一个选项第 1 组(这会弄乱我的仪表板,因为它会不断切换到用户不想看到的组) .

我尝试过这样的事情(但它不起作用):

    // first get the current selected option
    // (Note: I'm not using val, I'm using the actual text that's why you see .text() below)
    let currGrpSelection = $('#groupSelection option:selected').text();
    
    // then I sort
    $('#groupSelection').html(this.allGroups.sort(grpCollator.compare));

    // then I try to set the selected option back to the original one
    $('#groupSelection option:selected').text(currGrpSelection);

它不起作用,因为这段代码会发生这种情况:

从以下下拉列表中:

Group 1
Group 2   <- this is the one user selects

它变为:

Group 2   <- the code changes the first option to the one user selected! :(
Group 2

将不胜感激任何建议。我被这个问题困扰很久了...

标签: javascriptjquery

解决方案


我意识到我的错误。

尝试$("#someId selected:option").text()用作选定值不起作用。一旦我使用下拉列表,所选选项将自动成为第一个选项。

因此,我改为使用.val()。然后保存当前值,重新排序列表,并将列表的值重新设置为保存的值。


推荐阅读