6

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>
Uno Mein Ame
  • 1,060
  • 5
  • 16
  • 29

3 Answers3

3

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/

andy
  • 531
  • 5
  • 16
  • 1
    This solution doesn't seem to work reliably if using the keyboard for navigation. The firing of the "onclick" event seems erratic and doesn't always change in the ways I would expect, at least in my tests in Chrome. – cazort Apr 02 '19 at 19:06
2

It doesn't matter what library or framework you use, but this is quite simple. You are essentially looking for two things to be true:

  1. Test that the control was clicked.

  2. Test that a value (any value) has been selected, --or-- is still selected.

Number 2 can be achieved with something like...

var elem = document.getElementById("ddlViewBy");
var value = elem.options[elem.selectedIndex].value;

It's then a simple matter to test that it is non-empty.

Ian Atkin
  • 6,302
  • 2
  • 17
  • 24
  • i understand that i can do #1 with onclick. How do I get to #2? – Uno Mein Ame Dec 13 '12 at 09:45
  • correct me if I got you correctly. I do an onclick and then inside the function i test if there is anything selected. and if yes - i run the actual function? – Uno Mein Ame Dec 13 '12 at 09:58
  • Yes. That should give you what you need. – Ian Atkin Dec 13 '12 at 09:59
  • In addition to testing for ´click´ you should also check for keyboard events (a user might use the keyboard to change selection). In that case you should probably listen to ´keyup´ and when the enter key is pressed. – mqchen Aug 01 '13 at 18:07
0

If you use jQuery

You can try focus() event.

Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120