Skip to content
Advertisement

JavaScript to clear a select list when it is dropped down

Is there a way to trigger an event when an HTML select list is dropped down? I’m not asking about when it closed, but when you first drop it down.

I’d like to set the selectedIndex = -1 when the user clicks on the down arrow of the drop-down.

Most websites begin their drop-down with a blank entry, or a dummy entry like “Select…”. I’d like to just have the values themselves, and have the list clear itself whenever they click in.

This is what I started with, but it fires after they make a choice, which isn’t what I want – I want only when the list drops down.

JavaScript

This JSFiddle tries to use a click event, but of course that doesn’t let the user actually make a choice.

Advertisement

Answer

I modified @Dacre Denny’s answer and got it to work in Firefox, Chrome, and Edge.

Link to JSFiddle.

JavaScript

And, if you want to slap this behavior on all the select lists on a page, you can use this (JSFiddle). If anyone can see a good way to do this without calling eval() then I’m all ears.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement