select onchange same value

Uno Mein Ame picture Uno Mein Ame · Dec 13, 2012 · Viewed 7.1k times · Source

Is there a way to trigger an event if I open a dropdown select, and select the same value WITHOUT clicking away to switch focus?

I tried

  1. onblur, but it only works if I make an extra click outside the select.

  2. onchange, but it only works if I select a different value.

I need to trigger an event simply if I open the dropdown and select anything, regardless of whether it is the same or different.

<select name='show1' id='show1' onblur='dosomething(this);'>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>

Answer

andy picture andy · Dec 13, 2012

I think you'd have to use the onClick-event and store the previously selected item in a variable.

Here's a quick example which I think could use some refactoring :-)

    var dropboxOpen = false,
        oldItem     = null;
    function onClick(e) {
        if (dropboxOpen) {
            if (oldItem && oldItem === e.target.value) {
                console.log('same selected');
            }
            oldItem = e.target.value;   
        }        
        dropboxOpen = !dropboxOpen;
     }

http://jsfiddle.net/vtHPV/