I need to dynamically generate a drop-menu list from an array via JavaScript. I'm getting close, but while I can populate the array elements into the Bootstrap-enabled drop-menu that appears on my index.html page, I cannot select those individual elements that show up as drop menu items. I need to edit my code so I can click on one of those elements and run my second function, that populates the selection to an input field.
First, here's my script to iterate over the array:
<script>
let select = document.getElementById("selectJob");
let options = ["Job 1", "Job 2", "Job 3", "Job 4", "Job 5"];
for (let i = 0; i < options.length; i++) {
let opt = options[i];
let el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
</script>
And here's the second script I use:
<script>
function populateJobVal(val) {
document.getElementById("selection").value = val;
}
</script>
And here's the drop-menu section in my HTML where I'm trying to use this:
<div class="dropdown">
<button class="btn btn-default btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
Select Job Type to Schedule
<span class="caret"></span></button>
<ul class="dropdown-menu" id="selectJob">
<li>
<a href="#" role="button" onclick="populateJobVal(selectJob)" class="btn btn-link">
</a>
</li>
</ul>
</div>
Notice I am adding the "id" to the <ul> element. Should it be going elsewhere? I did try putting the "id" on the <li> element, but that makes all the array elements one clickable field, rather than each one being clickable.
Right now, when I click on the drop-menu button, the different jobs do appear. However, they are not individually clickable.
What do I need to edit in my code to make each element a clickable link?