Jarrod Roberson Jarrod Roberson - 1 year ago 70
jQuery Question

How to receive an event when selected option is the already selected option of a dropdown?


I want to dyanmically load a
with values from an AJAX call, and allow the user to select the first item in the list once it is loaded and after it gets focus, right now, the first item is the selected item and when you click the dropdown and click the first item nothing happens. I can't add any placeholder items that are not valid selections.


How do you fire the
event in jQuery when the currently selected option is reselected / not changed?

Given the following :

<select id="myoptions">
<option id="one" >Option 1</option>
<option id="two">Option 2</option>

Assuming that option
is selected, and I click on the dropdown and select
again, what event fires?

$('#myoptions').change(function() {
alert('You selected something!');

The above code works if I select something different, but if I select the currently selected option nothing happens.

In other words :

If I click on the dropdown and "select" the currently selected option, how do I get an event to fire?

Not Answers:

All these suggestions about
are not solutions, I need something that fires when I click on
Option 1
with the mouse when
Option 1
is already the selected option.

I tried using
and nothing happens then either.

None of the answers is a working solution for the use case of the very first time the dropdown is selected, and someone selects the default selected option. Nothing happens.

is not a solution, it doesn't happen until someone clicks somewhere else, which is too late in the game.

Answer Source

Working Solution:

First you have to explicitly set the first item to a selected state.

<select id="myoptions">
  <option id="one" selected="selected">Option 1</option>
  <option id="two">Option 2</option>

Then in your JavaScript you must explicitly remove the selected attribute.

$('#myoptions option:selected').removeAttr('selected');

$("#myoptions").on("change", function(){

This will then show a blank/empty drop down box on initialization. Which will allow you to select the first item in the list the first time you click on the dropdown because no option has the selected attribute anymore.

This has the benefit of having the look of a blank placeholder selection without actually having to have one and write all the convoluted logic to handle when it gets selected.

CodePen working example of the solution. Be sure and have your JavaScript debug console open before you click on the link or you won't see the desired effect.

This still doesn't solve the reselection issue that so many other people have asked about which is a similar problem, which I would like to use as a refresh mechanism, but I will tackle that in another question.