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!
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
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.
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()
Just an idea, but is it possible to put an onclick on each of the <option> elements?
<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).
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>
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>
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>
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.
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.
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>
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.
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;
}
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.
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.
2022 VANILLA JAVASCRIPT
...because this is a top hit on Google.
Original Poster did NOT ask for a JQuery solution, yet all answers ONLY demonstrate JQuery or inline SELECT tag event.
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);
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.
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/
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..
use jquery:
<select class="target">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<script>
$('.target').change(function() { doSomething(); });
</script>
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/
you should try using option:selected
$("select option:selected").click(doSomething);
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
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
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.
<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.
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>
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>
<select name="test[]"
onchange="if(this.selectedIndex < 1){this.options[this.selectedIndex].selected = !1}">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
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
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);
}
});
Related
I want to make the below function trigger anytime a blur event happens. The end goal is that anytime you click outside the textbox made in the below code, it puts you back in the text box. EXCEPT when you click into a dropdown box. The problem is that the below only works while in the original textbox. As it is now, once you're in a dropdown, you have free reign to click anywhere.
this.textbox = $('<input class="full-width" type="text" tabindex=1/>'); //Change the tab index number to the position you need it to be
this.host.append(this.textbox);
var _this = this;
this.textbox.blur(async function() {
await sleep(1);
if (!document.activeElement.className.match("dp-combobox__input dp-combobox__input--has-clear dp-combobox__input--has-arrow DropDownBoxes")) {
_this.textbox.focus();
_this.textbox.select();
}
});
function sleep(duration) {
return new Promise(resolve => {
setTimeout(() => {
resolve()
}, duration * 250)
})
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="dp-combobox__input dp-combobox__input--has-clear dp-combobox__input--has- arrow DropDownBoxes" style="font-family:Roboto;font-size:25px;color:Black;;font-style:normal;font-weight:normal;text-decoration:none;;height:100%" tabindex="-1">
Turns out you didn't need jquery at all.
var textbox = document.getElementsByClassName("dp-combobox__input dp-combobox__input--has-clear dp-combobox__input--has- arrow DropDownBoxes")[0];
document.body.addEventListener("click", function(evt){if(event.target!=document.getElementsByClassName("dropdown")[0]){textbox.focus();}})
html, body {width:100%;height:100%;margin:0;padding:4px;box-sizing:border-box;}
<input type="text" class="dp-combobox__input dp-combobox__input--has-clear dp-combobox__input--has- arrow DropDownBoxes" style="font-family:Roboto;font-size:25px;color:Black;font-style:normal;font-weight:normal;text-decoration:none;height:100%;" tabindex="-1">
<select class="dropdown">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
Note that I didn't remove the class names, since I wasn't sure what they were for. Also, when I ran the snippet it looked like there was just a text box and nothing else, so I added the dropdown for demonstration purposes.
What the code does is very simple - since click events propagate from the element to its parents, I just added a listener on the document's body for a click. After that, the script just checks if the original clicked element is the dropdown or not, and if it isn't, it focuses back on the textbox.
To be honest, I don't know what you were trying to do with this, since it always has to refer to an object (whether an element, or a function, or a variable). So, I just tried to solve your problem directly rather than try versions of your code.
Also, select and format has to be triggered from a click event from a user in most browsers, or it won't work (because if it did, just imagine how spam websites can abuse it and to what level).
I have a dropdown. On its select, the change event is fired. I again select the same element from the dropdown, it does not bind the change event to it.
One possible workaround is with click() event like the following:
var prevVal = "";
$('#mySelect').click(function(){
if($(this)[0].selectedIndex > 0){
var currVal = $(this).val();
if(prevVal != currVal){
console.log(currVal);
prevVal = currVal;
}
else prevVal = "";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
<option value="select">Please Select</option>
<option value="Arabic">Arabic</option>
<option value="Spanish">Spanish</option>
<option value="English">English</option>
</select>
Once option is selected from drop down, change event is not triggered on same option as there is no change with the selected value.
You can use click or focusout event, as per use.
Assuming your attached image is describing a language switch. At first select, the system will change content to Spanish.
At the second click for spanish nothing will happen since the Spanish is already selected at the first click. - The details of what happens in the logic of your solution is unknown to us.
Looking for an easy event to bind to that will fire any time an option is selected, even when it is the currently selected option. jQuery's .change() does not seem to fire when selecting the selected option again, but only the others (which makes sense, because it is a "change" event after all).
Is there anything else out there that is more or less identical to how change works, but will also fire when the selected element is selected again? Or will I need to get sloppy with click events or something?
<select id="select">
<option value="1">1</option>
<option value="2">2</option>
</select>
JS
$(function(){
$('#select option').click(function(){
alert($(this).val());
});
})
While Irfan's solution seems like a viable one, it did not work for me in Chrome. However, I ended up using a sort of workaround to solve this problem where I set a placeholder type option when the click event fires on the select box.
<select id="dropdown">
<option value="choose" disabled selected>Choose</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<script>
// When the dropdown is opened, the "choose" option is selected
$('#dropdown').on('click', function(){
$("#dropdown option").filter(function() {
return $(this).val() == "choose";
}).prop('selected', true);
// On change will always fire
$('#dropdown').on('change', doStuff);
});
function doStuff(){
// Grab the selected value before click changes it
let currentValue = $('#dropdown').val();
alert(currentValue);
/* Do other stuff with currentValue
Wait until second click that selects sets value to "choose"
when the user makes their selection, then set the selector
back to what the user chose
*/
setTimeout(function(){
$("#dropdown option").filter(function() {
return $(this).val() == order;
}).prop('selected', true);
}, 100);
}
</script>
The result is a slight delay before the selector shows what the user chose, but the change event always fires, since the active value was changed. This doesn't work as well in IE or FireFox, but if you can detect the browser being used, and combine this with Ifran's solution, you should be able to have this working on all browsers.
This is how I just solved a similar problem. Needed to display other fields when certain option was chosen. put the onclick on the select and passed the value of the option. Then just target the specific option you want in the function.
<select onclick='myfunc($(this).val())'>
<option value="" selected disabled hidden>pick</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
Jquery
function myfunc(val){
if(val == 'a'){
$("#a").show();
$("#b").hide();
}
if(val=='b'){
$("#a").hide();
$("#b").show();
}
}
The title seems confusing but what I want to do is...
I know how to handle only if the user select new option with this - $('select').change(function(){}).`
But not if the user wants to select the already selected option.
I've also tried with radio but same thing.
Okay for example I have a select with an option (red,blue,green).
<select>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="green">GREEN</option>
</select>
and I have this script:
$('select').change(function(){
var val = $(this).val();
alert(val);
});
When I select option 'blue' it alerts a value 'blue', then I select 'green' it alerts 'green' as well. but when I select 'green' again nothing happens.
This question comes to my attention as this is pretty basic stuff but no one actually dig into it further. OP has been using change(), but when you reselect the current selected option nothing is fired!
I tried click(), but it's firing before you can even choose an option.
With blur(), after you're done selecting nothing is fired because the the select element is still being focused, so you need to focus out like clicking outside for it to execute.
So I just suggested OP to switch to a radio type input then handle execution with click() event. That way you can still reselect already marked radio button.
But then I noticed that you just need to get the second click on <select> element because the first click opens the drop down list of options the second click returns the value of your selected option. So I came up with this:
$('select').click(function(){
var $this = $(this);
if ($this.hasClass('open')) {
alert($this.val());
$this.removeClass('open');
}else {
$this.addClass('open');
}
});
But now the problem is when you first click on <select> the drop down is being showned and we've also added the class 'open'. Then clicking elsewhere (without selecting an option) the drop down is hidden so when you click back on <select> the event is fired before you can even select an option.
So I added this code to fix that:
$(document).click(function(e){
var $select = $('select');
if (!$select.is(e.target)){
$select.removeClass('open'); //reset the steps by removing open
}
});
You can test it out in this jsfiddle. Cheers!
I think when <select> loses its focus is also a concern. So I added blur() event. See this update jsfiddle
i solved using onclick='this.value=-1' that reset the selection to nothing...
I have solved this problem by using:
$('#id_selec').on('click', 'option', function (e) {
value = $(this).val();
// ....
The handler works if you select any (including the already selected) option.
In instances where nothing should happen when the user selects the already-selected option I suppose it is a "feature" of the DOM rather than a bug to have no Event occur. However, if your code is doing more with <select> than making a simple selection it is also a nuisance, so I'm grateful others have tackled it here.
The current accepted answer is clever in the use of the click event to capture selection of an already selected <select> option, but if you are willing to specify the length of your list as (in this case) <select size=3>, you can simply set the selected value to "" from your "change" Event, and the same selection will trigger every time.
In this case the OP's example would change to:
HTML:
<select size=3>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="green">GREEN</option>
</select>
jQuery:
$('select').change(function(){
var val = $(this).val();
alert(val);
$('select').val("");
});
The only side-effect is that the selection element may now display to the user as three rows rather than one.
(Credit goes to Kirby L. Wallace for the idea of setting the select's value to "").
I am using the selectmenu plugin to style up some select menus on my site. I am using them for a filtering feature on my site. I want the user to only be able to filter by one menu at a time. So when a user selects an option on one menu the value on the other menu needs to go back to the default option.
I have a jsfiddle set up of what I'm trying to accomplish. It is almost working. I can get other menu to reset its value back to the first value in the list of options. The problem is the one I am changing does not change, it just stays at its default value.
Hopefully I've explained this well enough. Here's the link to the jsfiddle....
http://jsfiddle.net/dmcgrew/FBzFL/
Here's my code:
<select name="type" id="type">
<option value="*" selected="selected">Select Project Type</option>
<option value=".annualreport">Annual Report</option>
<option value=".branding">Branding</option>
<option value=".brochures">Brochures</option>
<option value=".retail-signage">Retail Signage</option>
<option value=".video">Video</option>
<option value=".web">Web Development</option>
</select>
<select name="industry" id="industry">
<option value="*" selected="selected" class="default">Select Project Industry</option>
<option value=".consumergoods">Consumer Goods</option>
<option value=".education">Education</option>
<option value=".entertainment">Entertainment</option>
<option value=".food">Food</option>
<option value=".healthcare">Healthcare</option>
</select>
$(function(){
$('select').selectmenu({
menuWidth: 170,
width: 170,
maxHeight: 600
});
$('select#type').change(function(){
$("select#industry").selectmenu("index", 0);
});
$('select#industry').change(function(){
$("select#type").selectmenu("index", 0);
});
});
Ah, figured it out!
When you change the value of one select drop-down programmatically, it'll fire any change listeners attached to the element. So even if you change the value of one select drop-down through the UI, both change listeners will end up being fired.
EDIT: Glad to hear you figured it out! Yes, I was trying to figure out a way to retain the change listeners, but it's much more difficult than I thought it would be, unless I'm missing something obvious. But setting up click listeners on the anchor elements should solve this problem nicely.
Just needed to detect a click() on the a within the dropdown instead of a change() on the select. Here's the new js:
$('ul#type-menu li a').click(function(){
$("select#industry").selectmenu("index", 0);
});
$('ul#industry-menu li a').click(function(){
$("select#type").selectmenu("index", 0);
});
You can unbind the listeners but a better solution in my opinion is to add and remove a class instead (see Suppress jQuery event handling temporarily). In your case:
$('select#type').change(function(){
if ($(this).hasClass('fired') == false) {
$('select#type').addClass('fired');
$('select#industry').selectmenu("index", 0);
}
$('select#industry').removeClass('fired');
});
$('select#industry').change(function(){
if ($(this).hasClass('fired') == false) {
$('select#industry').addClass('fired');
$("select#type").selectmenu("index", 0);
}
$('select#type').removeClass('fired');
});
Here is the jsfiddle: http://jsfiddle.net/JEfMD/