Creating a HTML5 datalist on the fly

后端 未结 4 1690
野的像风
野的像风 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 04:03

    With only the input present when the page is loaded :

    notice how I use "input.setAttribute('list','datalist')" and not "input.list = 'datalist' " directly.

    var datalist = document.createElement('datalist');
    datalist.id = "datalist";
    document.body.appendChild(datalist);
    ["Seattle", "Las Vegas", "New York", "Salt lake City"].forEach(function(data) {
      var option = document.createElement('option')
      option.value = data
      datalist.appendChild(option)
    });
    document.querySelector('#my-text-box').setAttribute('list', "datalist");

提交回复
热议问题