Creating a HTML5 datalist on the fly

后端 未结 4 1746
野的像风
野的像风 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:46

    You have to set the input element's list property as the id of the datalist:

    
    

    Working Code Example:

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

    OR: If you do not want to modify the HTML, you can use Element.setAttribute() to set the attribute in JavaScript:

    container.setAttribute('list','dlCities');
    

    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');
        container.setAttribute('list','dlCities'); // Set the attribute here
    
        dl.id = 'dlCities';
        for (; i < len; i += 1) {
            var option = document.createElement('option');
            option.value = optionList[i];
            dl.appendChild(option);
        }
        container.appendChild(dl);
    }
    fillDataList();

提交回复
热议问题