Is there an onSelect event or equivalent for HTML <select>?
Asked Answered
S

37

288

I have an input form that lets me select from multiple options, and do something when the user changes the selection. Eg,

<select onChange="javascript:doSomething();">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

Now, doSomething() only gets triggered when the selection changes.

I want to trigger doSomething() when the user selects any option, possibly the same one again.

I have tried using an "onClick" handler, but that gets triggered before the user starts the selection process.

So, is there a way to trigger a function on every select by the user?

Update:

The answer suggested by Darryl seemed to work, but it doesn't work consistently. Sometimes the event gets triggered as soon as user clicks the drop-down menu, even before the user has finished the selection process!

Sweven answered 15/3, 2009 at 4:13 Comment(7)
I can understand why you think so. I will keep it short. There are two inputs on my form. City (text field) and State (Selection). Initially, a city and its state is displayed. When the user selects a state, a search filter somewhere broadens its scope to "State-wide" instead of "City-specific".Sweven
strager, it's not an uncommon UI element. makes perfect sense in some situations. anther example would be composing a mass email, then you have a drop down on the right with "special fields" you can add quickly into the email, first name, opt out link, etc.Abeu
just as a side note... for inline events like onclick, onchange etc. you don't need the "javascript:" protocol prefix. on{event}="doSomething();" is just fine.Bindman
untested: how about onClick but applied to the option tags? obviously via a class, in an unobtrusive wayGuttersnipe
@The Disintegrator Only using click events fails to handle the use case where you select an option via keyboard. (Realize this is an ancient Question - adding for future visitors...)Vulva
Can @Sweven select the best answer? At least which is closer.. it would help othersGriddle
This is not at all what <select> is for. We should be using a list for this type of thing and handle with click events.Neddy
C
108

I needed something exactly the same. This is what worked for me:

<select onchange="doSomething();" onfocus="this.selectedIndex = -1;">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

Supports this:

when the user selects any option, possibly the same one again

Capable answered 13/9, 2012 at 10:46 Comment(7)
Worked great on firefox, but not on chrome or ie10Literatim
jsfiddle.net/ecmanaut/335XK works in osx Chrome 30, Safari 6, Firefox 17.Amytal
Also works in Win8 IE10, Win7 IE9, Win7 IE8, WinXP IE7 and IE6. Jsfiddle or IE shenanigans force you to use fiddle.jshell.net/ecmanaut/335XK/show/light directly for just-the-test, though - their editor view fails to load jQuery used in the example for readability. All above just tested with mouse interaction; to get this keyboard friendly this hack likely needs additional work, as at least old IEs happily trigger the change event before you've had a chance to get to choice "C".Amytal
Really great tip,. helped me resolved the inability to select the first optionTeleost
If a value is already selected, then tabbing through this will cause issues. As soon as the the field is navigated to the value will disappear which is a pretty unexpected user behavior. Also, when you tab off, you will have lost the selection, even though you've done nothing of the sort. Otherwise, good ideas.Becalm
Use e.g jQuery .blur() to restore the original selection if it is -1 at the point of loosing the focus.Bestiality
I used onblur to reset the index because with onfocus I had to select the element twice after changing focus... but that is not ideal either...Condescendence
S
90

Here is the simplest way:

<select name="ab" onchange="if (this.selectedIndex) doSomething();">
    <option value="-1">--</option>
    <option value="1">option 1</option> 
    <option value="2">option 2</option>
    <option value="3">option 3</option>
</select>

Works both with mouse selection and keyboard Up/Down keys whes select is focused.

Sarcoma answered 22/10, 2011 at 8:28 Comment(6)
But this won't do anything "when the user selects ... the same one again," right?Diamante
Note that the comment from @KayZhu is only half correct: the correct thing to do is to check that "selectedIndex" is greater than or equal to zero (or greater than -1). There's no "type()" function, and "selectedIndex" will never be undefined anyway.Mozart
@T.J.Crowder You are correct -- not sure what I was thinking when I wrote the second half. I've deleted the original comment and for the purpose of not confusing others, here is the original comment (please note that the first half is correct, and the second part is wrong): This will not work as expected for the first option which has index 0: 0 is false in JS so doSomething() will not be executed. Instead, use if(type(this.selectedIndex) != undefined; doSomething()Loads
This answer has the most upvotes, but it doesn't address the problem! The doSomething() function is not triggered when the user selects the already-selected option. See this plunk, where the background color only changes if you select a different option than the currently selected one.Lot
FWIW: If you want to only invoke doSomething() when one specific option is selected, for instance "option 3" in the above example, use if (this.selectedIndex==4) whereby the number "4" represents the numeric index of options, NOT the specified value! (i.e., "option 3" is the fourth option of <select name="ab">).Brainchild
onchange is only triggered after the select is blurredPrince
B
15

2022 VANILLA JAVASCRIPT

...because this is a top hit on Google.

Original Poster did NOT ask for a JQuery solution, yet all existing answers ONLY demonstrate JQuery or inline SELECT tag event. Here is how you would do it using Vanilla Javascript instead:

Use an event listener with the 'change' event.

const selectDropdown = document.querySelector('select');
selectDropdown.addEventListener('change', function (e) { /* your code */ });

... or call a seperate function:

function yourFunc(e) { /* your code here */ }

const selectDropdown = document.querySelector('select');
selectDropdown.addEventListener('change', yourFunc);
Bisector answered 19/8, 2022 at 19:3 Comment(0)
H
12

I had the same problem when I was creating a design a few months back. The solution I found was to use .live("change", function()) in combination with .blur() on the element you are using.

If you wish to have it do something when the user simply clicks, instead of changing, just replace change with click.

I assigned my dropdown an ID, selected, and used the following:

$(function () {
    $("#selected").live("change", function () {

    // do whatever you need to do

    // you want the element to lose focus immediately
    // this is key to get this working.
    $('#selected').blur();
    });
});

I saw this one didn't have a selected answer, so I figured I'd give my input. This worked excellently for me, so hopefully someone else can use this code when they get stuck.

http://api.jquery.com/live/

Edit: Use the on selector as opposed to .live. See jQuery .on()

Harod answered 2/2, 2012 at 16:33 Comment(4)
thanks! .blur() helps. In IE7, jQuery's change event is triggered twice if no .blur() in the code.Reunionist
How does this help with the problem expressed in the question, i.e. that nothing happens until the selection is changed?Diamante
@Diamante it's been several years since this question, not sure -- I may have read the question wrong and been confused.Harod
For anyone looking now, .live has been fully removed as of 1.9 api.jquery.com/live/#live-events-handler. Use .change as a shortcut api.jquery.com/change/#change-handlerFlout
A
10

Just an idea, but is it possible to put an onclick on each of the <option> elements?

<!-- DOESN'T WORK -->
<select>
  <option onclick="doSomething(this);">A</option>
  <option onclick="doSomething(this);">B</option>
  <option onclick="doSomething(this);">C</option>
</select>

Another option could be to use onblur on the select. This will fire anytime the user clicks away from the select. At this point you could determine what option was selected. To have this even trigger at the correct time, the onclick of the option's could blur the field (make something else active or just .blur() in jQuery).

Akeylah answered 15/3, 2009 at 4:15 Comment(6)
@Darryl This didn't actually work as expected. Sometimes the event gets triggered even before user completes the selection. See the update that I added to the question.Sweven
Putting event handlers on the options will fail in all versions of IE! webbugtrack.blogspot.com/2007/11/…Bindman
Works in firefox.Mcniel
that list can be looong.Keewatin
Doesn't work in Chromium, needs also answer below from user1845327Nola
Regardless of whether this works, its arguably an anti-pattern. If you end up with a lot of lists with many options, this pattern impairs browser performance. All of the performance-promoters will tell you from experience that you are better off with only a few top-level event-listeners that handle events as they bubble up. Putting an event listener on every single option is a way to start a bad habit that may bite you or someone else later. There's also the fact that it makes setup code ugly since you're adding the event in a loop!Bisector
B
7

If you really need this to work like this, I would do this (to ensure it works by keyboard and mouse)

  • Add an onfocus event handler to the select to set the "current" value
  • Add an onclick event handler to the select to handle mouse changes
  • Add an onkeypress event handler to the select to handle keyboard changes

Unfortunately the onclick will run multiple times (e.g. on onpening the select... and on selection/close) and the onkeypress may fire when nothing changes...

<script>
  function setInitial(obj){
    obj._initValue = obj.value;
  }
  function doSomething(obj){
    //if you want to verify a change took place...
    if(obj._initValue == obj.value){
      //do nothing, no actual change occurred...
      //or in your case if you want to make a minor update
      doMinorUpdate();
    } else {
      //change happened
      getNewData(obj.value);
    }
  }
</script>


<select onfocus="setInitial(this);" onclick="doSomething();" onkeypress="doSomething();">
  ...
</select>
Bindman answered 24/7, 2009 at 13:22 Comment(1)
thanks for the pointer, I bound my listener to onfocus + onchange now and it works :)Condescendence
C
7

The onclick approach is not entirely bad but as said, it will not be triggered when the value isn't changed by a mouse-click.
It is however possible to trigger the onclick event in the onchange event.

<select onchange="{doSomething(...);if(this.options[this.selectedIndex].onclick != null){this.options[this.selectedIndex].onclick(this);}}">
    <option onclick="doSomethingElse(...);" value="A">A</option>
    <option onclick="doSomethingElse(..);" value="B">B</option>
    <option onclick="doSomethingElse(..);" value="Foo">C</option>
</select>
Centenarian answered 22/11, 2012 at 14:26 Comment(0)
M
7

I know this question is very old now, but for anyone still running into this problem, I have achieved this with my own website by adding an onInput event to my option tag, then in that called function, retrieving the value of that option input.

<select id='dropdown' onInput='myFunction()'>
  <option value='1'>1</option>
  <option value='2'>2</option>
</select>

<p>Output: </p> 
<span id='output'></span>

<script type='text/javascript'>
function myFunction() {
 var optionValue = document.getElementById("dropdown").value;
 document.getElementById("output").innerHTML = optionValue;
}
</script>
Mulvihill answered 9/11, 2020 at 0:33 Comment(1)
does not seem to support re-selectionCondescendence
W
6

To properly fire an event every time the user selects something(even the same option), you just need to trick the select box.

Like others have said, specify a negative selectedIndex on focus to force the change event. While this does allow you to trick the select box, it won't work after that as long as it still has focus. The simple fix is to force the select box to blur, shown below.

Standard JS/HTML:

<select onchange="myCallback();" onfocus="this.selectedIndex=-1;this.blur();">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

jQuery Plugin:

<select>
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

<script type="text/javascript">
    $.fn.alwaysChange = function(callback) {
        return this.each(function(){
            var elem = this;
            var $this = $(this);

            $this.change(function(){
                if(callback) callback($this.val());
            }).focus(function(){
                elem.selectedIndex = -1;
                elem.blur();
            });
        });
    }


    $('select').alwaysChange(function(val){
        // Optional change event callback,
        //    shorthand for $('select').alwaysChange().change(function(){});
    });
</script>

You can see a working demo here.

Wretched answered 21/1, 2013 at 19:54 Comment(3)
This works with Chrome, but not with IE9: when I click on the control, its text disappears and it does not drop-down.Clough
The problem with this is that it nukes the current selection. If the current selection is B and I click on the pulldown, the checkmark shows up next to A! But A is not really selected, because if I slide off the menu and release the mouse button (aborting the menu) the selection goes blank. The selection also goes blank if you tab to the pulldown, which you might easily do if you were tabbing through to some other part of the form, not expecting to do any damage along the way. (Press tab on your jsfiddle and you'll see what I mean.)Lot
I can't select anything with this configCondescendence
G
5

Going to expand on jitbit's answer. I found it weird when you clicked the drop down and then clicked off the drop down without selecting anything. Ended up with something along the lines of:

var lastSelectedOption = null;

DDChange = function(Dd) {
  //Blur after change so that clicking again without 
  //losing focus re-triggers onfocus.
  Dd.blur();

  //The rest is whatever you want in the change.
  var tcs = $("span.on_change_times");
  tcs.html(+tcs.html() + 1);
  $("span.selected_index").html(Dd.prop("selectedIndex"));
  return false;
};

DDFocus = function(Dd) {
  lastSelectedOption = Dd.prop("selectedIndex");
  Dd.prop("selectedIndex", -1);

  $("span.selected_index").html(Dd.prop("selectedIndex"));
  return false;
};

//On blur, set it back to the value before they clicked 
//away without selecting an option.
//
//This is what is typically weird for the user since they 
//might click on the dropdown to look at other options,
//realize they didn't what to change anything, and 
//click off the dropdown.
DDBlur = function(Dd) {
  if (Dd.prop("selectedIndex") === -1)
    Dd.prop("selectedIndex", lastSelectedOption);

  $("span.selected_index").html(Dd.prop("selectedIndex"));
  return false;
}; 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="Dd" onchange="DDChange($(this));" onfocus="DDFocus($(this));" onblur="DDBlur($(this));">
  <option>1</option>
  <option>2</option>
</select>
<br/>
<br/>Selected index: <span class="selected_index"></span>
<br/>Times onchange triggered: <span class="on_change_times">0</span>

This makes a little more sense for the user and allows JavaScript to run every time they select any option including an earlier option.

The downside to this approach is that it breaks the ability to tab onto a drop down and use the arrow keys to select the value. This was acceptable for me since all the users click everything all the time until the end of eternity.

Galliot answered 8/6, 2016 at 22:1 Comment(3)
You can get rid of the prop warnings by passing in this instead of $(this). However, I don't get all the intended behavior out of this; it doesn't alert when I re-select the same option.Mccully
Note: onchange is triggered when adding removing options to a select box via JS. Not just when a user selects an itemTirzah
@Mccully I fixed the errors in this if it is still helpful. I think I was testing this in the application itself and when I copied it out I forgot to rename a variable. Should work in the editor and make more sense now.Galliot
A
5

first of all u use onChange as an event handler and then use flag variable to make it do the function u want every time u make a change

<select

var list = document.getElementById("list");
var flag = true ; 
list.onchange = function () {
if(flag){
document.bgColor ="red";
flag = false;

}else{
document.bgColor ="green";
flag = true;
}
}
<select id="list"> 
<option>op1</option>
<option>op2</option>
<option>op3</option>
</select>
Aristippus answered 15/8, 2017 at 22:17 Comment(0)
D
5

This may not directly answer your question, but this problem could be solved by simple design level adjustments. I understand this may not be 100% applicable to all use-cases, but I strongly urge you to consider re-thinking your user flow of your application and if the following design suggestion can be implemented.

I decided to do something simple than hacking alternatives for onChange() using other events that were not really meant for this purpose (blur, click, etc.)

The way I solved it:

Simply pre-pend a placeholder option tag such as select that has no value to it.

So, instead of just using the following structure, which requires hack-y alternatives:

<select>
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

Consider using this:

<select>
  <option selected="selected">Select...</option>
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

So, this way, your code is a LOT more simplified and the onChange will work as expected, every time the user decides to select something other than the default value. You could even add the disabled attribute to the first option if you don't want them to select it again and force them to select something from the options, thus triggering an onChange() fire.

At the time of this answer, I'm writing a complex Vue application and I found that this design choice has simplified my code a lot. I spent hours on this problem before I settled down with this solution and I didn't have to re-write a lot of my code. However, if I went with the hacky alternatives, I would have needed to account for the edge cases, to prevent double firing of ajax requests, etc. This also doesn't mess up the default browser behaviour as a nice bonus (tested on mobile browsers as well).

Sometimes, you just need to take a step back and think about the big picture for the simplest solution.

Danidania answered 8/6, 2018 at 11:40 Comment(0)
N
4

Add an extra option as the first, like the header of a column, which will be the default value of the dropdown button before click it and reset at the end of doSomething(), so when choose A/B/C, the onchange event always trigs, when the selection is State, do nothing and return. onclick is very unstable as many people mentioned before. So all we need to do is to make an initial button label which is different as your true options so the onchange will work on any option.

<select id="btnState" onchange="doSomething(this)">
  <option value="State" selected="selected">State</option>  
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>


function doSomething(obj)
{
    var btnValue = obj.options[obj.selectedIndex].value;

    if (btnValue == "State")
    {
      //do nothing
      return;
    }

    // Do your thing here

    // reset 
    obj.selectedIndex = 0;
}
Nakisha answered 30/11, 2019 at 5:42 Comment(0)
S
3

Actually, the onclick events will NOT fire when the user uses the keyboard to change the selection in the select control. You might have to use a combination of onChange and onClick to get the behavior you're looking for.

Sue answered 8/4, 2009 at 5:31 Comment(2)
Yes, I would have to.. but the problem I am facing is a separate one orthogonal to the concern you raise. The onclick event on <option> is getting fired even before the user completes his selection, which seems to make it impossible to use.Sweven
Events fire in Chrome when you press enter after having moved the selection to a new itemDesk
D
3

The wonderful thing about the select tag (in this scenario) is that it will grab its value from the option tags.

Try:

<select onChange="javascript:doSomething(this.value);">
<option value="A">A</option>
<option value="B">B</option>
<option value="Foo">C</option>
</select>

Worked decent for me.

Dammar answered 26/8, 2011 at 16:35 Comment(1)
does not support re-selectionCondescendence
H
2

What I did when faced with a similar Problem is I added an 'onFocus' to the select box which appends a new generic option ('select an option'or something similar) and default it as the selected option.

Hygrothermograph answered 10/4, 2012 at 10:46 Comment(0)
D
2

you should try using option:selected

$("select option:selected").click(doSomething);
Driggers answered 27/10, 2012 at 5:12 Comment(0)
B
2

So my goal was to be able to select the same value multiple times which essentially overwrites the the onchange() function and turn it into a useful onclick() method.

Based on the suggestions above I came up with this which works for me.

<select name="ab" id="hi" onchange="if (typeof(this.selectedIndex) != undefined) {alert($('#hi').val()); this.blur();}" onfocus="this.selectedIndex = -1;">
    <option value="-1">--</option>
    <option value="1">option 1</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
</select>

http://jsfiddle.net/dR9tH/19/

Blurb answered 2/7, 2014 at 18:12 Comment(1)
Same drawback as with the other onfocus="this.selectedIndex=-1" solutions: Current selection gets nuked if you tab to the component, or if you mouse off the menu without selecting anything. Press tab on your fiddle to see what I mean. (Also notice you get a blank value and not '--' when you do this. That's because selectedIndex=-1 does not get you to <option value="-1">; it would be a slight improvement here to use onfocus="this.selectedIndex=0". This is a half-decent workaround, but I don't like losing the current selection just because I peeked at the menu, or even just tabbed to it.Lot
C
2

Very old question, but right now the event on click works perfectly, that is, it triggers even when the user re-selects the same option.

Test yourself:

const e = document.getElementById('myOptions')

e.addEventListener('click', () => {
  const text = e.options[e.selectedIndex].text;
  console.log(text)
})
<select id="myOptions">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>
Cornelius answered 15/12, 2022 at 7:31 Comment(0)
P
1

Kindly note that Event Handlers are not supported for the OPTION tag on IE, with a quick thinking..I came up with this solution, try it and give me your feedback:

<script>
var flag = true;
function resetIndex(selObj) {
    if(flag) selObj.selectedIndex = -1;
    flag = true;
}
function doSomething(selObj) {
    alert(selObj.value)
    flag = false;
}
</script>
<select onchange="doSomething(this)" onclick="resetIndex(this)">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>

What I'm doing here actually is resetting the select index so that the onchange event will be triggered always, true that you we lose the selected item when you click and it maybe annoying if your list is long, but it may help you in someway..

Parenthood answered 24/7, 2009 at 13:12 Comment(0)
N
1

use jquery:

<select class="target">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

<script>
    $('.target').change(function() { doSomething(); });
</script>
Newberry answered 26/11, 2011 at 23:29 Comment(0)
G
1

Here's my solution, completely different to any else on here. It uses the mouse position to figure out if an option was clicked as oppose to clicking on the select box to open the dropdown. It makes use of the event.screenY position as this is the only reliable cross browser variable. A hover event has to be attached first so it can figure out the controls position relative to the screen before the click event.

var select = $("select");

var screenDif = 0;
select.bind("hover", function (e) {
    screenDif = e.screenY - e.clientY;
});
select.bind("click", function (e) {
    var element = $(e.target);
    var eventHorizon = screenDif + element.offset().top + element.height() - $(window).scrollTop();
    if (e.screenY > eventHorizon)
        alert("option clicked");
});

Here is my jsFiddle http://jsfiddle.net/sU7EV/4/

Garlic answered 3/10, 2012 at 11:1 Comment(1)
Doesn't work in Safari or Chrome for OS X. The alert is never triggered.Lot
C
1

What works for me:

<select id='myID' onchange='doSomething();'>
    <option value='0' selected> Select Option </option>
    <option value='1' onclick='if (!document.getElementById("myID").onchange()) doSomething();' > A </option>
    <option value='2' onclick='if (!document.getElementById("myID").onchange()) doSomething();' > B </option>
</select>

In that way, onchange calls 'doSomething()' when the option changes, and onclick calls 'doSomething()' when onchange event is false, in other words, when you select the same option

Cb answered 3/5, 2014 at 19:55 Comment(1)
Doesn't work for me in Safari or Chrome for OS X. jsfiddle.net/drskot/wLvL4pkwLot
G
1

Try this (event triggered exactly when you select option, without option changing):

$("select").mouseup(function() {
    var open = $(this).data("isopen");
    if(open) {
        alert('selected');
    }
    $(this).data("isopen", !open);
});

http://jsbin.com/dowoloka/4

Geometric answered 19/6, 2014 at 12:15 Comment(0)
V
1

The one True answer is to not use the select field (if you need to do something when you re-select same answer.)

Create a dropdown menu with conventional div, button, show/hide menu. Link: https://www.w3schools.com/howto/howto_js_dropdown.asp

Could have been avoided had one been able to add event listeners to options. If there had been an onSelect listener for select element. And if clicking on the select field didn't aggravatingly fire off mousedown, mouseup, and click all at the same time on mousedown.

Vasyuta answered 13/6, 2017 at 21:22 Comment(0)
M
1
<script>
function abc(selectedguy) {
alert(selectedguy);
}
</script>

<select onchange="abc(this.selectedIndex);">
<option>option one</option>
<option>option two</option>
</select>

Here you have the index returned, and in the js code you can use this return with one switch or anything you want.

Moncada answered 7/8, 2017 at 19:37 Comment(0)
P
1

The best solution I have found is to add a disabled option as the first element within your select element so that all other items will be available to respond to click in the onchange event.

<select onchange="doSomething()">
  <option disabled selected value> -- select an option -- </option>
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>
Pasteurizer answered 29/6, 2022 at 4:35 Comment(0)
G
0

Try this:

<select id="nameSelect" onfocus="javascript:document.getElementById('nameSelect').selectedIndex=-1;" onchange="doSomething(this);">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
</select>
Germinative answered 8/7, 2012 at 10:20 Comment(0)
D
0

A long while ago now but in reply to the original question, would this help ? Just put onClick into the SELECT line. Then put what you want each OPTION to do in the OPTION lines. ie:

<SELECT name="your name" onClick>
<option value ="Kilometres" onClick="YourFunction()">Kilometres
-------
-------
</SELECT>
Delicacy answered 31/3, 2013 at 22:54 Comment(0)
I
0
<select name="test[]" 
onchange="if(this.selectedIndex < 1){this.options[this.selectedIndex].selected = !1}">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
Invulnerable answered 7/4, 2014 at 9:38 Comment(0)
D
0

I had faced a similar need and ended up writing a angularjs directive for the same -

guthub link - angular select

Used element[0].blur(); to remove the focus off the select tag. Logic is to trigger this blur on second click of the dropdown.

as-select gets triggered even when user selects the same value in the dropdown.

DEMO - link

Devin answered 22/12, 2016 at 19:26 Comment(0)
E
0

There are a few things you want to do here to make sure it remembers older values and triggers an onchange event even if the same option is selected again.

The first thing you want is a regular onChange event:

$("#selectbox").on("change", function(){
    console.log($(this).val());
    doSomething();
});

To have the onChange event trigger even when the same option is selected again, you can unset selected option when the dropdown receives focus by setting it to an invalid value. But you also want to store the previously selected value to restore it in case the user does not select any new option:

prev_select_option = ""; //some kind of global var

$("#selectbox").on("focus", function(){
    prev_select_option = $(this).val(); //store currently selected value
    $(this).val("unknown"); //set to an invalid value
});

The above code will allow you to trigger onchange even if the same value is selected. However, if the user clicks outside the select box, you want to restore the previous value. We do it on onBlur:

$("#selectbox").on("blur", function(){
    if ($(this).val() == null) { 
       //because we previously set an invalid value 
       //and user did not select any option
        $(this).val(prev_select_option);
    }
});
Ezaria answered 31/5, 2020 at 4:34 Comment(0)
C
0

Another solution is using the onMouseUp event. OnMouseUp works also with the same option re-selected as well as changed option.

Only disadvantage. The code is called when the dropdown box is openemd and a second time when the selection is made. Keep that in mind for AJAX requests. If this is not harming your logic you can use it as a simple inline hack.

<select id="bla" onmouseup="console.log( document.getElementById('bla').options[document.getElementById('bla').selectedIndex].value );">
  <option value="0">A</option>
  <option value="1">B</option>
</select>
Cunningham answered 8/1, 2021 at 19:13 Comment(0)
C
0

The only solution that worked for me was totally resetting the SELECT on "onFocus" event. This way, the SELECT always "changes" on "onChange" event:

$('select').on('focus', function(ev) {
    var $select = $(this);
    var options = $select.html();
    $select.empty();
    $select.append(options);
});

$('select').on('change', function(ev) {
    // Now the select element ALWAYS fires onChange
});
Cloistral answered 25/10, 2021 at 8:18 Comment(0)
N
-1

what about changing the value of the select when the element gains focus, e.g (with jquery):

$("#locationtype").focus(function() {
    $("#locationtype").val('');
});

$("#locationtype").change(function() {
    if($("#locationtype").val() == 1) {
        $(".bd #mapphp").addClass('show');
        $("#invoerform").addClass('hide');
    }
    if($("#locationtype").val() == 2) {
        $(".lat").val('');
        $(".lon").val('');
    }
});
Nena answered 16/4, 2011 at 10:56 Comment(0)
T
-2

You can use onChange: http://www.w3schools.com/TAGS/tag_Select.asp

Copied from http://www.faqs.org/docs/htmltut/forms/_SELECT_onChange.html onChange designates a JavaScript to run when the user chooses one of the options. This means that an action is initiated immediately when the user chooses an item, not when a "submit" button is pressed.

Trueman answered 15/3, 2009 at 4:39 Comment(1)
As mentioned in the question, this does not work as it is only when the value is changed, not when any event is selected including the currently selected one.Akeylah
D
-2

I found out this solution .

set the selectedIndex of select element to 0 initially

//set selected Index to 0

doSomethingOnChange(){

     blah ..blah ..

     set selected Index to 0

}

call this method onChange event

Damek answered 1/2, 2012 at 16:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.