0

I have button and a select box. i want to open the dropdown by click on the button.

<button id="showDropdown"></button>
<select id="selectME">
  <option>Select</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

I have tried this js script:

$("#showDropdown").click(function(){
  $("#selectME").click(); 
});

This is not working for me. Please help.

DevzValley
  • 115
  • 1
  • 1
  • 11
  • 3
    Does this answer your question? [Can I open a dropdownlist using jQuery](https://stackoverflow.com/questions/360431/can-i-open-a-dropdownlist-using-jquery) – Kamran Dec 27 '19 at 14:09
  • May be that article will help you https://medium.com/browserquirks/browserquirk-programmatically-opening-a-select-box-4ca745a8468f – maximelian1986 Dec 27 '19 at 14:29
  • Try using select2 jQuery plugin and trigger open event on click. – Ahed Kabalan Dec 27 '19 at 14:45

1 Answers1

0

You can clone the <select> element, append it to the body and show it.

$('#showDropdown').click(function(){
  var select = $('#selectME');
  
  var clone = select.clone().removeAttr('id');
  
  clone.val(select.val()).css({
      overflow: 'auto',
      position: 'absolute',
      left: select.offset().left,
      top: select.offset().top + select.outerHeight(),
      width: select.outerWidth()
  });
        
  clone.attr('size', clone.find('option').length)
  
  clone.change(function() {
      select.val(clone.val());
  });
        
  clone.on('click blur keypress',function(e) {
   if(e.type !== 'keypress' || e.which === 13)
      $(this).remove();
  });
  
  clone.appendTo('body').focus();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="showDropdown">Select me</button>
<select id="selectME">
  <option>Select</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
Tân
  • 1
  • 15
  • 56
  • 102