Creating a HTML5 datalist on the fly

后端 未结 4 1692
野的像风
野的像风 2021-01-20 03:43

I\'m trying to create a datalist on they fly and attach it to an existing input element. But nothing happens (no dropdown arrow is shown) jQuery would be acceptable, too.

4条回答
  •  一生所求
    2021-01-20 03:59

    JS

        var optionList = ["Seattle", "Las Vegas", "New York", "Salt lake City"];
    
        function fillDataList() {
    
            var container = document.getElementById('my-text-box'),
            i = 0,
            len = optionList.length,
            dl = document.createElement('datalist');
    
            dl.id = 'dlCities';
            for (; i < len; i += 1) {
                var option = document.createElement('option');
                option.value = optionList[i];
                dl.appendChild(option);
            }
            container.appendChild(dl);
        }
    
    fillDataList();
    

    HTML

    
    

提交回复
热议问题