Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a <select /> via label, ::before, or programatically?

Any solution need only work in WebKit browsers.

The internet is littered with attempts to make this work - some who claim to have it working and some who claim it can't be done. In my experience, none of the suggested methods have worked. Is this simply impossible?

Supposing I have a select like <select id="mySelect" />

Things I've tried:

  • select::before -- Is added to the DOM, but doesn't render
  • <label for="mySelect" /> -- Does nothing when clicked/tapped
  • document.querySelector('select').click() -- Does nothing
  • The method from this answer (React-specific) -- Cannot assign a click handler or any other handler that can programmatically open the select to begin with

I'm open even to a jQuery solution, even though we're using React and we would be loading jQuery solely for triggering the select to open.

On third party select components: The goal is to trigger the mobile OS's native select control for the user, so something like React-Select is not suitable.

like image 608
Slbox Avatar asked Dec 02 '25 23:12

Slbox


1 Answers

A dirty solution updated from here (https://stackoverflow.com/a/249219/3684265)

var _select = document.getElementById("test");

_select.addEventListener("mouseout",function(){
  this.size = 1;
});

_select.addEventListener("mouseover",function(){
  this.size = 4;//set to show the number that you want
});
<select id="test">
  <option value="1">1</option>
  <option value="1">2</option>
  <option value="1">3</option>
  <option value="1">4</option>
  <option value="1">5</option>
  <option value="1">6</option>
</select>

like image 68
imvain2 Avatar answered Dec 04 '25 13:12

imvain2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!