I have some code to generate a drop-menu whose contents come from an array. That part is working. However, I need to then pass the value selected from the drop-menu into my populateJobVal()
function when a user clicks on one of the menu elements - so that that value will get printed to the input field. Right now when I run this code, what gets printed to the input field is [object HTMLUListElement]
.
I assume all I need to do here is pass the correct value to my populateJobVal()
, however, so far it hasn't worked as expected. I've tried adjusting the code as follows:
a.setAttribute('onclick', 'populateJobVal(opt)');
... However, nothing at all prints to the input field in this case. What do I need to pass here? Or am I missing something?
<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 a = document.createElement("a");
a.textContent = opt;
a.setAttribute('href', '#');
a.setAttribute('onclick', 'populateJobVal(selectJob)'); // What to pass here?
a.setAttribute('class', 'btn btn-link');
let li = document.createElement("li");
li.appendChild(a);
select.appendChild(li);
}
function populateJobVal(val) {
document.getElementById("selection").value = val;
}
</script>
My relevant HTML code looks like 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">
</ul>
</div>
I changed the way you're adding the click event, much easier to pass the opt
argument. The previous way you were passing the entire list.
Replace
a.setAttribute('onclick', 'populateJobVal(opt)');
With
a.addEventListener('click', () => {
populateJobVal(opt)
}); // Look here
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 a = document.createElement("a"); a.textContent = opt; a.setAttribute('href', '#'); a.addEventListener('click', () => { populateJobVal(opt) }); // Look here a.setAttribute('class', 'btn btn-link'); let li = document.createElement("li"); li.appendChild(a); select.appendChild(li); } function populateJobVal(val) { debugger document.getElementById("selectJob").value = val; }
<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"> </ul> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.