简体   繁体   中英

Javascript fill dropdown from array and select some options

I want to select the Option where month[i][2] = "1" , there can be more than one selected.

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);
        }
    }
}

Add attribute multiple to the select element and then, when the condition is met for a given array entry, add attribute selected to the corresponding, newly created option like this 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> 

When you run the snippet you will see two items selected because I have added ["1", "August", "1"] to the list.

And you can change your code a little bit to make it more readable like this.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM