I've been trying to "catch" the click event on a select element, then add <option>
fields dynamically based on some other Elements in the DOM, and then fire an event to open the dropdown of the select element.
I sucessfully managed to catch the click event and add <option>
fields. I'm having trouble opening the select with my current approach tho. What I tried:
$(document).ready(function(){
$(document).on("mousedown", "#select-box", function(e){
e.preventDefault();
var options = "";
$(".some-div").each(function(i, obj){
var id = $(obj).attr("id");
options += '<option value="' + id + '">' + id + '</option>';
});
$("#select-box").html(options);
// - Open the select dropdown here -
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="some-div" id="div1">
<div class="some-div" id="div2">
<div class="some-div" id="div3">
<select id="select-box">
<option value="" disabled="" selected="">Select Div</option>
</select>
So if you run that snippet, click the select and inspect it in DevTools, it does have the dynamic options I need. But I don't know how to actually open it. Some answers here on StackOverflow suggested firing the mousedown
event manually by using
$("#select-box").trigger("mousedown");
but that obviously doesn't work, because that's the very event I'm catching right from the start.
I'd appreciate if someone could point me in the right direction
I think you're trying to trigger the default behavior, so remove
e.preventDefault();
I think it's also stopping your code from functioning the way you think (?). I'm not seeing 3 IDs get added to the dropdown.