admin管理员组

文章数量:1353278

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>

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>
Share Improve this question edited Dec 13, 2012 at 9:49 Uno Mein Ame asked Dec 13, 2012 at 9:30 Uno Mein AmeUno Mein Ame 1,0906 gold badges16 silver badges30 bronze badges 4
  • it will be better, if you will show us, what you have tried till now. – Ravi Commented Dec 13, 2012 at 9:38
  • as i said, i tried onchange and i tried onblur, and none of that works as intended – Uno Mein Ame Commented Dec 13, 2012 at 9:44
  • I know, so show us your coding and problem. That will help to know your exact problem. – Ravi Commented Dec 13, 2012 at 9:46
  • stackoverflow./questions/647282/… – Alex from Jitbit Commented Dec 26, 2018 at 22:03
Add a ment  | 

3 Answers 3

Reset to default 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/vtHPV/

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.

If you use jQuery

You can try focus() event.

本文标签: javascriptselect onchange same valueStack Overflow