Select already selected item in dropdown/select - list - javascript

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,
},
});
}
},

Related

How to open disabled fields in Selenium

I'm trying to fill a form using Selenium, but the form has a disabled field.
Disabled field
The field is only editable when I modify the field above it.
Open field
When I set the value directly using the code below, the field is not open for editing
js.executeScript("document.getElementById('field_id').value='" + brand + "'");
Example
I tried to simulate the click in the field, press the tab key, press the enter key, but none had any effect.
Is there any way for me to trigger the same event that the user is performing on the screen to release the field through selenium or javascript?
In the HTML code, the options are not listed, so the options are loaded from a javascript function that is executed after filling the first field
Options
Because I really liked it I'll copy Tschallackas Intro:
Your test is flawed. You are not following user behaviour.
Sadly I totally disagree with the rest of the answer :(
I would like to ask WHY are you trying to use JavaScript?
Is this something a real User would do? I really doubt it!
The crucial thing with End2End-Tests is to simulate your User behaviour as close as possible. Therefore I would suggest to use the Webdriver to do things like that in your Seleniumtest.
Select dropdown = new Select(webdriver.findElement(By.id("field_id")));
dropdown.selectByVisibleText("ONESOURCE");
(Assuming you are using Java by the tag on your question)
Your test is flawed. You are not following user behaviour.
You are doing:
js.executeScript("document.getElementById('field_id').value='" + brand + "'");
Which tries to change a value on a dropdown. This doesn't work because dropdowns work via a selectedIndex, which you can use to get the correct value from the options collection on the dropdown element.
Also, when a user changes a value, a change event is triggered, which notifies other scripts that listen to that event that something has changed. You need to emulate this too to trigger your change script.
js.executeScript("let select = document.getElementById('field_id');"+
"select.selectedIndex = 1;/* change this to the value corresponding to the correct index of the value you wish to test. */"+
"select.dispatchEvent(new Event('change'));");
See the example below for how the javascript should work.
document.getElementById('field_id').addEventListener('change', (e) => {
if(e.target.options[e.target.selectedIndex].value > 1) {
document.getElementById('the_disabled').disabled = false;
}
else {
document.getElementById('the_disabled').disabled = true;
}
});
document.getElementById('trigger').addEventListener('click',() => {
let select = document.getElementById('field_id');
select.selectedIndex = 1;// change this to the value corresponding to the correct index of the value you wish to test.
select.dispatchEvent(new Event('change'));
});
<select id="field_id">
<option value="1">--none--</option>
<option value="2">COMPANY A</option>
<option value="3">COMPANY B</option>
</select>
<BR/>
<select id="the_disabled" disabled="disabled">
<option value="0">--none--</option>
<option value="1">SELECT A</option>
<option value="2">Select B</option>
</select>
<BR/>
<button id="trigger">Trigger selenium emulation</button>

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>

<HTML> Can't select same values in drop down list. Validation <HTML>

I want to be able to validate my drop down lists.
There are 6 destinations, and if the user was to select Cardiff in the "Departure" drop down, then if they was to select Cardiff again in the "Destination" drop downn, it should give a message box saying 'Destination can't be the same as Departure'.
This needs to be done in HTML and JavaScript/JQuery.
Thanks
Departure: <br> <select>
<option value="" disabled selected>Please Select</option>
<option>Birmingham</option>
<option>Bristol</option>
<option>Cardiff</option>
<option>Liverpool</option>
<option>London</option>
<option>Manchester</option>
</select><br><br>
Destination: <br><select>
<option value="" disabled selected>Please Select</option>
<option>Birmingham</option>
<option>Bristol</option>
<option>Cardiff</option>
<option>Liverpool</option>
<option>London</option>
<option>Manchester</option>
</select><br><br>
Very quick example but essentially you can do something like this:
Fiddle: http://jsfiddle.net/6hojsqhr/
$('#select1, #select2').on('change',
function () {
if ($('#select1').val() == $('#select2').val()) {
// Display message
}
else {
// Remove message if displayed
}
}
);
Well I am feeling slightly called out so let me explain what is happening here.
$('#select1, #select2').on('change',
First I select the two inputs we want to test against and attach a change event to them. This will fire this event every time the input's value changes and loses focus.
if ($('#select1').val() == $('#select2').val()) {
// Display message
}
else {
// Remove message if displayed
}
In this function we get both values of the two inputs we want to test for equivalent values. If they are the same we display the message. If not don't do anything or in some cases remove a displayed message.
Again this is a very quick solution that can be much more dynamic and thought out depending on your specific scenario. This is very simple JavaScript/jQuery. I would recommend doing some reading and perhaps free courses online that can teach these basics. A simple google search will pull up a ton of examples of code like this and websites that teach how to do this.

Multiple Dynamic Javascript Dropdowns?

I have currently got a 2-tier javascript drop down box attached to my form, and i am looking to add another 3-tiers, but completely seperate to my current javascript and can't unfortunately figure it out (quite new to javascript :( )
Here what I have so far, it all works ( not even sure what framework to select on fiddle for it to display properly lol :( the embarassment haha
Any help is appreciated <3
This will probably be enough code for you to get the idea.
jsFiddle here
I used jQuery to get handles to the various DOM elements. Here is a quite decent resource for browsing all jQuery selectors, events, effects, css, etc - despite the source. (Just keep hitting Next Chapter)
First, this is your code for catching the optone select element's change event, removed from inline javascript (which is never a good idea):
$('select[name=optone]').change(function() {
var selval = $(this).val();
setOptions(selval);
});
Simple enough, yes?
I left your first setOptions function as is, because it works. However, I wrote the next function setOptions2() in jQuery, to show you how much less typing is required.
To catch the next select element's change event:
$('select[name=opttwo]').change(function() {
var sel2val = $(this).val();
alert('You selected: ' + sel2val);
setOptions2(sel2val);
$('#selthreeDiv').show();
});
Notice in my jsFiddle that I added a hidden div containing the 3rd select control, and I display that control when the 2nd select is changed...
Hopefully this will be of assistance.
ok I did something like this and it worked for me.
your new javascript
function setOptions2(chosen) {
var selbox = document.myform.optthree;
selbox.options.length = 0;
if (chosen == "1") {
selbox.options[selbox.options.length] = new Option('Worked', ' ');
}
}
then added some new html
<select name="opttwo" size="1" onchange="setOptions2(document.myform.optone.options[document.myform.optone.selectedIndex].value);" >
<option value="Please Select Prompt Category" selected="selected">Please Select Prompt Category</option>
</select>
<select name="optthree" size="1">
<option value="Please Select Prompt Category" selected="selected">Please Select Prompt Category</option>
</select>

Click already selected option in select box

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.

Categories

Resources