Click already selected option in select box - javascript

This seems like it should be easy, but the limitations of the <select> object are rather irritating. I have a select box with four options, and when you navigate to a page, the option is set to the page you are on. I want to make it so that the user can refresh the page by selecting the same option - that is, selecting the option that's already selected.
Unfortunately, the onclick event doesn't work across browsers. Most people recommend using onchange, but that doesn't work in the case I'm talking about. The approach I've been taking is to add an extra item at the top that holds what's currently selected and does nothing when clicked on, and then switch to that option after firing the onchange event, so that when the user re-selects the option they're actually changing. That's awkward though, because in the drop-down there are two of the same item, and I shouldn't have to do it.
What is a good cross-browser way to solve this problem? Something not terribly complicated and something in regular JavaScript would be preferable.

This might help:
function onFocus(element){
element.setAttribute('old-value',element.value);
element.value='';
console.log('reset');
}
function onBlur(element){
if(element.value=='')
element.value = element.getAttribute('old-value');
element.removeAttribute('old-value');
}
function onChange(element){
console.log('New Value : '+ element.value);
}
<select id="mySelect" onfocus="onFocus(this)" onchange="onChange(this)" onblur="onBlur(this);">
<option value="" style="display:none;"></option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>

Here you go with the solution
$("select[id=mySelect] option").click(function(){
alert("HI");
});
This will alert -HI- everytime a click is made on an option. The change has also been made in the select box and event is also been performed.

Related

How to select a dropdown element on a website using javascript code?

I am writting a javascript program that needs to be able to select an element on a dropdown and then continue browsing. My problem is that even though I can select a dropdown element and that I can see the dropdown change on the website, the element I have selected doesn't seem to be "registered" and when I continue my browsing, the dropdown is back to the default option.
I figured out that maybe the website needs a mouse click to register the change so I have tried clicking on the dorpdown after selecting the right option but it still doesn't work.
Here is the different codes I have tried and which seems to both have the same problem :
//first try:
document.getElementById('SingleOptionSelector-0').selectedIndex = 2;
//second try :
document.getElementById('SingleOptionSelector-0').value = '3';
I tried to click on the dropdown menu like this:
document.getElementById('SingleOptionSelector-0').click();
But it doesn't expand. It's like the click is not registered which seems very strange to me because when I click somewhere else on the web-page it works just fine
I have seen a lot of questions about how to interact with a dropdown menu,but no one else seems to have the problem that when you change the value it is not registered by the web-page
The relevant HTML is below:
<select class="single-option-selector single-option-selector-product-template_original product-form__input" id="SingleOptionSelector-0" data-index="option1">
<option value="1">Hamburger</option>
<option value=" 2">fries</option>
<option value="3">Coke</option>
<option value="4">Diet Coke</option>
</select>
edit : It seems that I was not clear enough. An example of my problem is the website https://www.xhibition.co/collections/air-jordan/products/jordan-23-engineered-full-zip-jacket?variant=29510378848328 . When I use one of these methods to change the "size" dropdown, I can see it changing but when going to the basket, the size of the element I just added is the default one ('M'). That's what I mean by the website "not registering" the dropdown change.
Try this.
document.getElementById('myDropDown').value = "2"
Your question is kind of vague, but I think the sample below should give you a good idea of how to get and set select element values and also how to use addEventListener to know when a change event has taken place:
const selectEl0 = document.querySelector('#SingleOptionSelector-0');
const selectEl1 = document.querySelector('#SingleOptionSelector-1');
const onChange = e => selectEl1.value = e.target.value;
selectEl0.addEventListener('change', onChange)
The second select element will update it's value when the first one changes:<br/>
<select class="single-option-selector single-option-selector-product-template_original product-form__input" id="SingleOptionSelector-0" data-index="option1">
<option value="1">Hamburger</option>
<option value="2">fries</option>
<option value="3">Coke</option>
<option value="4">Diet Coke</option>
</select>
<select class="single-option-selector single-option-selector-product-template_original product-form__input" id="SingleOptionSelector-1" data-index="option1">
<option value="1">Hamburger</option>
<option value="2">fries</option>
<option value="3">Coke</option>
<option value="4">Diet Coke</option>
</select>

How to show modal box whenever choose the select option using jQuery? [duplicate]

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.
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/
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);
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);
}
});

Selected attribute of select options is not updating automatically

I have multiple selects on my page, each has multiple options.
However, If I select an option then the attribute selected of the option is not updating. Shouldn't this happen automatically?!
Example:
<select id="browsers">
<option value="Firefox">Bing</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
By inspecting the DOM with the developer console, you should see, that the selected attribute is not changing even after selecting another option.
However I found a workaround. To solve this issue we can use this code:
$(document).on("change","select",function() {
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
Example:
$(document).on("change","select",function() {
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="browsers">
<option value="Firefox">Bing</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
This works kind of. However, If I select another option than the default option, e.g. Chrome and reload the page, then the option Chrome is still selected even after reload, BUT the selected attribute still points to Internet Explorer!
Which is the best approach to solve this?
My idea is to run through all selects on $(document).ready() and select the option where the selected attribute points to.
But why does this all not happen automatically?
Is it a bug or a feature?
The selected attribute defines if an element should be selected on pageload. If you post a form with a select element, the chosen option will be the one posted, regardless of the initial selected element.
What do you need the selected-attribute for in your case?
Edit: Based on your comments I made a fiddle
Fiddle 1 https://jsfiddle.net/q3fpafov/1 selects like you want
Fiddle 2 https://jsfiddle.net/bge9bsa7/2/ only files available for a chosen language are shown
I hope it's somewhere along the lines of what you're looking for.
The reason for your option still being selected when you reload is browser based. But the selected-attribute does nothing for the usability of the option. Also, it won't change because you don't change the way the HTML-element itself is being rendered (at page load)
Note: selected="selected" is not necessary, simply selected attribute will work as well.
When present, select attribute specifies that an option in select should be pre-selected when the page loads.
Also, the pre-selected option will be displayed first in the drop-down list.
Those 2 should be only effects of the selected attribute.
Note the keywords - when the page loads. He is either there or not when a browser loads the page.
If you wanna make it dynamic you need to use JavaScript. What do you wanna achieve with this? Having attribute selected on the correct element when reloading page or programmatically select the correct element after the page has been loaded?
If you simply wanna make element selected there is easier way trough either value:
jQuery("#browsers[value='the value of the one you like']").attr('selected','selected');
Or by index (mind, indexes start at 0 not 1):
document.getElementById("browsers").selectedIndex = "2";
The problem before was, that after selecting an option and reloading the page, the option was remembered during page reload, even though the attribute selected pointed to another option.
I solved it by calling the function below everytime. The function finds out which is the truly selected option, even after page reload.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="downloadSelect" id="select_179">
<option value="-">Please select</option>
<option value="link_2748" selected="selected">Deutsch</option>
<option value="link_2749">Chinese</option>
</select>
<button onclick="return showSelectedOption('select_179');">Show Option Text</button>
<script>
function showSelectedOption(pSelectID)
{
var text;
$("#"+pSelectID)
.find("option")
.each(function(){
if ($(this).prop("selected")) {
text = $(this).text();
}
});
console.log(text);
}
</script>
You can check the value of the select when it changes to see what it has been changed to.
var select = document.getElementById('browsers');
select.addEventListener('change', function(e) {
localStorage.setItem('browser', this.value);
});
var browser = localStorage.getItem('browser');
if (browser) {
select.value = browser;
}
<select id="browsers">
<option value="Firefox">Firefox</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
edit
So, I missed the part about storing the value so that it persists when the page is reloaded, and depending on the OP's use case, I would suggest using localStorage to save the value when it is changed, and to read from it when the page is reloaded.
I have edited the snippet to reflect this (code is simplified)

Catch attribute change on automatically changed elements

I want to create two selections on my webpage which will be connected to each other so that both selections will always be the same. Let me explain in a mock example:
I have a webpage with two selects:
<select class="myselector">
<option value='1'>1
<br>
</option>
<option value='2'>2
<br>
</option>
</select>
<select class="myselector">
<option value='1'>1
<br>
</option>
<option value='2'>2
<br>
</option>
</select>
Note: in reality, I have more than just the two selects and I want them all to be connected.
Now, I want the webpage to automatically set the second selector to the value of the first if the first is changed. I also want to perform some other things on the select that has changed, so I also want the change event to trigger on the other selector. My first thought was simply to do this:
function valChange() {
myfun();
$('.myselector').val($(this).val());
}
$('.myselector').on('change', valChange);
This does what I need in that it changes the selected values so they match
This does not trigger the change event in the other select, so myfun runs only once
My next thought was to add $('.myselector').change(); to the end of the valChange function, but this (naturally) causes an infinite loop of change events.
My question is, therefore:
How can I trigger the change event in only the elements that have been
changed automatically (not by a user)?
I think it could be done by having both the change and the click event, but that just seems wrong and ugly to me.
EDIT: I found a way to solve my problem through the use of jquery selectors. If there exists a more elegant way of solving the problem, I will still be happy to see it though.
function valChange() {
myfun()
var others = $('.myselector[value!=' + $(this).val() + ']');
others.val($(this).val());
others.change();
}
$('.myselector').on('change', valChange);
JSfiddle for my solution:
http://jsfiddle.net/5xum/svjbdxgs/
you can use each method of jquery
function valChange() {
var _this = $(this)
$('.myselector').each(function(){
myFun();
$(this).val(_this.val());
});
}
$('.myselector').on('change', valChange);
here is fiddle for the same fiddle link

Select already selected item in dropdown/select - list

I've been searching for an answer to this question for quite some time now, with no luck, or buggy solutions at max.
The problem im facing is that i have a select element which (obviously) doesn't fire the "onchange" event when selecting the already selected item.
Like this:
<select onchange="alert(this.value);">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
Now, say i select item 1 first.
Then afterwards i need to be able to select item 1 again.
This feature is extremely important to the success of the project I'm working on.
Any help is greatly appreciated.
Edit: (More info)
This functionality is needed as im working on a project with a google maps where users are presentet with a dropdown to quickly jump to a country (Eg you select "Spain" in the dropdown, google maps sets spain as your view.
the problem comes when you want to go to spain, then drag around the map, and end up in italy. Now you want to go back to spain, but you cant select it from the dropdown until you select something else first. My boss doesn't like that :)
Edit2: Solution
So by now theres a few solution.
One of them is to throw the action onblur (when unfocusing the control) this could work, as i could blur the list onchange, but still for people selecting the same item again, the trigger to blur the control wont go, and unless they switch focus by them self, they wont see the changes to the map.
Still i cannot understand why it should be so hard to find some event that excutes on option select / click / blur or whatever.. ill keep looking myself, and check back here a tad later.
Edit 3: Final solution
Right so i finally managed to get this working, not exactly as it was ment to be, but close enough, atleast for now anyways.
The solution i came up with was to add a "Please select country" option at the top of the select.
Then on change, i would change the text, and value of "Please select country" to that of the selected item, and reset the selectedindex to 0.
This way, when selecting, say, Spain, it will be at the top of the list in a disabled state, and further down in a working state. so now you can click spain in the middle of the list to go back to spain even though it is still selected (the top item is)
Quite neat, idea was supplied from a coworker.
script is as following:
var dummyOption;
function setdummyCountry(obj)
{
var selectedOption = obj.options[obj.selectedIndex];
if (dummyOption != null) {
dummyOption.text = selectedOption.text;
dummyOption.value = selectedOption.value;
}
else {
dummyOption = document.createElement("option");
dummyOption.text = selectedOption.text;
dummyOption.value = selectedOption.value;
dummyOption.setAttribute("disabled", "true");
obj.options[0] = dummyOption;
}
obj.selectedIndex = 0;
}
<select onchange="setdummyCountry(this);">
<option value="">Please select country</option>
<option value="ES">spain</option>
<option value="SE">sweden</option>
<option value="NO">norway</option>
</select>
i hope this will help someone!
And to those who tried to help me thank you for your ideas and time.
I think there is no way change event is gonna fire if the same item is selected. We were facing the same issue so what we did was a simple usability hack: When an item is selected we show to the user the item selected in a span and reset the value of dropdown to its default value (--Select--).
HTH
this is maybe not excactly what do you want, but this another alternative that you can decide.
after select the option, get it back to default(the empty one/first) option
<select onchange="alert(this.value);this.value='';">
<option value='' selected='selected'></option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
or you can make
<select onblur="alert(this.value);">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
but this way will call your function (alert) when user leave/blur/unfocus the list :p
I was looking for the solution for the same scenario 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
you can use onclick function and maintain a count for that, once you get same target.value twice, then you can perform your onchange fuctionality there.
I have implemented this in Vue.js
Select block:
<select
id="status"
name="status"
#change="
onChangeStatus(un.id, $event)
"
#click="
onChangeStatus(
un.id,
$event,
'same'
)
"
class="form-control"
:value="un.status"
>
<option value="Uncleaned">Uncleaned</option>
<option value="Partially Taken for cleaning">
Partially Taken for cleaning
</option>
<option value="Fully Taken for cleaning">
Fully Taken for cleaning
</option>
</select>
Kept count=0 initially.
I have used same function on both events, checked conditions and returned data accordingly
onChangeStatus(id, e, type) {
if (type === "same") {
if (e.target.value === "Partially Taken for cleaning") {
this.count += 1;
if (this.count === 2)
this.$router.push({
name: "NewPage",
params: {
id: id,
status: e.target.value,
},
});
}
} else {
this.$router.push({
name: "NewPage",
params: {
id: id,
status: e.target.value,
},
});
}
},

Categories

Resources