I have searched the posts to find a solution to what I would like to do. I want to create a list for <datalist> using a JavaScript array. I found a for loop that worked for someone else, and I modified it slightly to work with a 2D array. I have used the code below on JSFiddle, and it works, but when I include it into my larger code, the <datalist> does now show up even though the code is simply copied and pasted into my larger code.
Also, I'm not sure how to change the code below to jQuery, if you could help with that I would greatly appreciate it as well.
var test = [
['text1',1,2,3,4],
['text2',1,2,3,4],
['text3',1,2,3,4],
['text4',1,2,3,4],
['text5',1,2,3,4],
['text6',1,2,3,4],
['text7',1,2,3,4],
];
var options = '';
for(var i = 0; i < test.length; i++) {
options += '<option value="'+test[i][0]+'" />';
document.getElementById('maltList').innerHTML = options;
}
<input name ="malt" list="maltList"/>
<datalist id="maltList"></datalist>
You can use the jQuery#append method to add a list of options (mapped from the data in your test array using Array#map) to your datalist. Since the code you had before was working as a snippet, though, I'm not sure whether this will actually help you in whatever context it had failed previously.
Let me know if you get any error messages and I will try to help you resolve them.
var test = [
['text1',1,2,3,4],
['text2',1,2,3,4],
['text3',1,2,3,4],
['text4',1,2,3,4],
['text5',1,2,3,4],
['text6',1,2,3,4],
['text7',1,2,3,4],
]
$('#maltList').append(test.map(function (e) {
return new Option(e[0])
}))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name ="malt" list="maltList"/>
<datalist id="maltList"></datalist>