HTML datalist values from array in JavaScript
Asked Answered
H

7

35

I have a simple program which has to take the values from the text file on a server and then populate the datalist as the selection in the input text field.

For this purpose the first step I want to take is that I want to know how the JavaScript array can be used as a datalist option dynamically.

My code is:

<html>
<script>

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

</script>

<input name="anrede" list="anrede" />
<datalist id="anrede">
  <option value= mycars[0]></option>
  <option value="Frau"></option> 
</datalist>
</html>

I want to populate the input text field containing the datalist as suggestions from the array. Also here I haven't taken into account the array values. Actually I need not two datalist options but an arbitrary number (depending on the array length).

Hindermost answered 29/7, 2013 at 16:34 Comment(0)
M
31

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

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;
<input name="car" list="anrede" />
<datalist id="anrede"></datalist>
Matchbox answered 29/7, 2013 at 16:45 Comment(0)
H
50

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.

Humes answered 18/2, 2016 at 2:44 Comment(1)
Thanks! The .innerHTML method in the accepted answer didn't work for my situation, but yours did.Cablet
M
31

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

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;
<input name="car" list="anrede" />
<datalist id="anrede"></datalist>
Matchbox answered 29/7, 2013 at 16:45 Comment(0)
M
18

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>
Mincemeat answered 3/5, 2017 at 10:46 Comment(0)
T
5

There is also a constructor to create an option: new Option()

const
  dtl_anrede = document.getElementById('anrede')
, myCars     = ['Herr', 'Frau']
  ;

myCars.forEach(car => dtl_anrede.appendChild(new Option('', car)))
<input name="car" list="anrede" />
<datalist id="anrede"></datalist>
Thaine answered 26/8, 2021 at 15:4 Comment(0)
T
3

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/

Tetracaine answered 29/7, 2013 at 16:50 Comment(0)
C
3

A more performant way of doing this is to use fragment.

Append the option elements to the <datalist> dynamically, but instead of adding every item from the list, use fragment to avoid reflow and render them into the DOM just once.

var datalist = document.getElementById('anrede');
var fragment = document.createDocumentFragment();

var myCars = ['Herr', 'Frau'];

// Prepare the option elements to be rendered.
myCars.forEach(function(car) {
  var option = document.createElement('option');
  var text = document.createTextNode(car);

  option.value = car;
  option.appendChild(text);
  fragment.appendChild(option);
});

// Append all of them to DOM.
datalist.appendChild(fragment);
<input name="anrede" list="anrede" />
<datalist id="anrede"></datalist>
Cogitable answered 20/9, 2020 at 12:0 Comment(1)
From the same fragment docs: "The performance benefit of DocumentFragment is often overstated. ... as demonstrated in this benchmark." Not saying it's a bad idea, just not definitively more performant.Carangid
E
1
const datalist = document.getElementById('anrede');
for (const item of myCars) 
  datalist.appendChild(new Option(null,item));

This is the most performant and concise way to do it.

Extravehicular answered 15/5, 2023 at 15:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.