Javascript从数组填充下拉列表并选择一些选项

时间:2018-06-05 14:42:07

标签: javascript dropdown selected

我想选择month[i][2] = "1"的选项,可以选择多个。

function addOption_list() {
    var month = [["1", "January", ""], [["3", "Mars", ""], ["4", "April", ""], ["5", "May", ""], ["2", "February", "1"]]

    var select = document.getElementById('select_table');
    for (var i=0; i < month.length;++i){
        var option = document.createElement("OPTION"),
            txt = document.createTextNode(month[i][1]);
        option.appendChild(txt);
        option.setAttribute("value",month[i][0]);
        if(month[i][2]!=''){
            // February need to be selected
            select.insertBefore(option,select.lastchild);
        } else {
            // others not
            select.insertBefore(option,select.lastchild);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

将属性multiple添加到select元素,然后,当满足给定数组条目的条件时,将属性selected添加到相应的新创建的option像这样option.setAttribute('selected', true);

function addOption_list() {
    var month = [["1", "August", "1"], ["1", "January", ""], ["3", "Mars", ""], ["4", "April", ""], ["5", "May", ""], ["2", "February", "1"]];

    var select = document.getElementById('select_table');
    for (var i=0; i < month.length;++i){
        var option = document.createElement("OPTION"),
            txt = document.createTextNode(month[i][1]);
        option.appendChild(txt);
        option.setAttribute("value", month[i][0]);
        if(month[i][2] === '1'){
            option.setAttribute('selected', true);
            select.insertBefore(option, select.lastchild);
        } else {
            select.insertBefore(option,select.lastchild);
        }
    }
}

addOption_list();
<select multiple id="select_table"></select>

当您运行代码段时,您会看到两个项目已选中,因为我已将["1", "August", "1"]添加到列表中。

您可以稍微更改一下代码,使其更具可读性。

function addOption_list() {
  const month = [["1", "August", "1"], ["1", "January", ""], ["3", "Mars", ""], ["4", "April", ""], ["5", "May", ""], ["2", "February", "1"]];
  const select = document.getElementById('select_table');

  month.forEach(mnth => {
    const option = document.createElement('OPTION');
    option.textContent = mnth[1];
    if (mnth[2] === '1') { option.setAttribute('selected', true) };
    select.append(option);
  });
}

addOption_list();
<select multiple id="select_table"></select>