May 13, 2013

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

Jarrod Roberson’s Question:

Objective:

I want to dyanmically load a select 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.

Question:

How do you fire the .change 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>
</select>

Assuming that option one is selected, and I click on the dropdown and select one 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. I tried using .click and nothing happens then either.

In other words :

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

NOTE:

All these suggestions about trigger 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.

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.

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

Use .trigger() function to fire custom events on elements.

$("#yourelementid").trigger('change'):

This way you can trigger the change event on element with id yourelementid

Now since you want this to happen when you click on the dropdown and select the previous element. Adding a click event should do it.

$("#yourelementid").on('click', function() {
    $(this).trigger('change');
});
...

Please fill the form - I will response as fast as I can!