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).
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>