Html datalist values from array in javascript

随声附和 提交于 2019-12-03 10:08:20

I'm not sure if I understood your question clearly. Anyway, try this:

<input name="car" list="anrede" />
<datalist id="anrede"></datalist>

<script type="text/javascript">
  var mycars = new Array();
  mycars[0]='Herr';
  mycars[1]='Frau';

  var options = '';

  for(var i = 0; i < mycars.length; i++)
    options += '<option value="'+mycars[i]+'" />';

  document.getElementById('anrede').innerHTML = options;
</script>

This is an old question and already sufficiently answered, but I'm going to throw the DOM method in here anyway for anyone that doesn't like to use literal HTML.

<input name="car" list="anrede" />
<datalist id="anrede"></datalist>

<script>
var mycars = ['Herr','Frau'];
var list = document.getElementById('anrede');

mycars.forEach(function(item){
   var option = document.createElement('option');
   option.value = item;
   list.appendChild(option);
});
</script>

Here's the fiddle.

If you are using ES6 you could do it this way, this is Paul Walls techniques with ES6 syntax.

const list = document.getElementById('anrede'); 

['Herr','Frau'].forEach(item => {
  let option = document.createElement('option');
  option.value = item;   
  list.appendChild(option);
});
<input name="car" list="anrede" />
<datalist id="anrede"></datalist>

You can do it jQuery way - but on the other hand, since you are processing data on the server, you might generate HTML directly there (just a suggestion).

<script>

var mycars = new Array();
mycars[0]='Herr';
mycars[1]='Frau';

$(document).ready( function() {
    $(mycars).each( function(index, item) {
        var option = $('<option value="'+item+'"></option>');
        $('#anrede').append(option);
    });
});

</script>

<input name="anrede" list="anrede" />
<datalist id="anrede">
    <!-- options are filled in the script -->
</datalist>

Here's a JSFiddle with this code so you can immediatelly try it: http://jsfiddle.net/mBMrR/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!