0

I want to show all the contents of select element (for below snippet) on focus when navigating to it using tab key.

select {
  width: 200px;
  border: 1px solid #aaa;
  border-radius: 4px;
  height: 28px;
  overflow: hidden;
}
<select id="" class="select2" >
  <option value="" disabled selected>Select Fruit</option>
  <option value="1">Apple</option>
  <option value="2">Banana</option>
</select>

A solution I've found in jQuery but I want the same function in plain JavaScript which I'm not able to do.

jQuery code :-

$('.select2').select2({
  minimumResultsForSearch: 20
});

$(document).on('focus', '.select2.select2-container', function (e) {
  var isOriginalEvent = e.originalEvent
  var isSingleSelect = $(this).find(".select2-selection--single").length > 0
  if (isOriginalEvent && isSingleSelect) {
    $(this).siblings('select:enabled').select2('open');
  } 
});
Razneesh
  • 1,147
  • 3
  • 13
  • 29
  • What have you tried in raw javascript then? – TKoL Dec 23 '19 at 14:14
  • `select2` does not, based on my brief reading, use the browser-default Select element - it replaces it with its own entirely custom implementation. I wouldn't be that surprised to learn that you cannot trigger a select element to open up programmatically – TKoL Dec 23 '19 at 14:15
  • https://stackoverflow.com/questions/430237/is-it-possible-to-use-js-to-open-an-html-select-to-show-its-option-list – TKoL Dec 23 '19 at 14:16
  • Select2 is a component library built on jQuery that adds a lot of features. Rewriting a library that depends on jQuery to not de[pend on jQuery is far too much to ask of volunteers. – Heretic Monkey Dec 23 '19 at 14:32

1 Answers1

0

Try something like

<select id="select2" class="select2" >
  <option value="" disabled selected>Select Fruit</option>
  <option value="1">Apple</option>
  <option value="2">Banana</option>
</select>



document.getElementById("select2").addEventListener("focus", myFunction);
 function myFunction() {
     var e = document.getElementById("select2");
      console.log(e.options[e.selectedIndex].value);
 }
CMartins
  • 3,247
  • 5
  • 38
  • 53