I am wondering if anyone has any experience using a JQuery plugin that converts a html
<select>
<option> Blah </option>
</select>
combo box into something (probably a div) where selecting an item acts the same as clicking a link.
I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack.
Your advice, experience and recommendations are appreciated.
The simple solution is to use
$("#mySelect").change(function() {
document.location = this.value;
});
This creates an onchange event on the select box that redirects you to the url stored in the value field of the selected option.
I'm not sure where you want to link to when you click the Div, but given something like this perhaps would work:
<select id="mySelect">
<option value="1">Option 1</option>
<option value="2">Option 2</options>
</select>
<div id="myDiv"/>
and the following JQuery creates a list of <div> elements, a goes to a URL based on the value of the option:
$("#mySelect option").each(function() {
$("<div>" + $(this).text() + "</div>").appendTo($("#myDiv")).bind("click", $(this).val(), function(event) {
location.href = "goto.php?id=" + event.data;
});
});
$("#mySelect").remove();
Does this do what you want?
If you're going to have a lot of select boxes that you want to allow to use as redirects, without having to define them independently, try something similar to:
$("[id*='COMMON_NAME']").change(function() {
document.location = this.value;
});
And have your select boxes be named accordingly:
<select id="COMMON_NAME_001">...</select>
<select id="COMMON_NAME_002">...</select>
This creates a onchange event for all IDs containing "COMMON_NAME" to do a redirect of the <option> value.
This bit of javascript in the 'select':
onchange="if(this.options[this.selectedIndex].value!=''){this.form.submit()}"
It's not ideal (because form submissions in ASP.NET MVC which I'm using don't appear to use the routing engine for URLs) but it does its job.
Related
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>
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)
I'm facing an issue in selecting the dropdown first value after selecting it for the first time. When the dropdown options slidedown to select, the first value would be selected by default,bcoz of which I'm not able to select the first value. I'm using JQuery mobile framework and I'm writing custom JS to change the dropdown. I need to handle this dropdown only using custom JS and cannot make the dropdown work with this custom logic due to some other issue with my project.
Here first value im referring as 'US' from dropdown
The solution for this issue would be really appreciated. Thanks in advance.
HTML:
<select id="drpDwn">
<option value="" disabled="disabled">select</option>
<option value="US">US</option>
<option value="AU">AU</option>
<option value="NZ">NZ</option>
</select>
JS:
$(document).on('change', '#drpDwn', function () {
var index = $(this)[0].selectedIndex;
$(this).attr('selectedIndex', index);
$(this).find('option').removeAttr('selected');
$(this).find('option').eq(index).attr('selected', 'selected');
$(this).siblings('span').html($(this).find('option').eq(index).text());
});
http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js
http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css
Check out this JSFiddle
The difference maker was modifying:
$(this).find('option').removeAttr('selected');
Into:
$(this).find('option:not(:selected)').removeAttr('selected');
When 'change' was triggered, the selected attribute is added to the new option, so you were stripping it away from everything even the new selection. That's why the option never changed.
Using :not(:selected) came in handy then since it will only strip away the attribute from things that weren't the current selected option.
I am just starting out with some java script in an asp.net mvc web site.
I current have a form which I am working on.
The first field which the user is prompted with is a combobox / select (in html)
here is the code for it:
<select name="select">
#foreach (var item in Model.networks)
{
<option value="">#Html.DisplayFor(modelItem => item.name)</option>
}
</select>
Now my next field depends on the option which they chose from the combo box.
How can I populate the next field based on the option they chose in the combo box?
So when the user navigates to the page they will ave a combo box populated with all the options. Below that will be empty fields. When the user selects a option in the combo box I want it to then populate the empty fields with the corresponding data from the option which was chosen.
How do I go about doing this?
Please give the newby answer as in the method in which it will be done. I am assuming that I will be using java script for it?
Although I cannot understand your question in detail, I hope I can help you.
HTML
If you have a select element that looks like this:
<select id=dropdown>
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
Plain Javascript solution
Running this code:
var element = document.getElementByID('dropdown');
var current = e.options[e.selectedIndex].value;
Would make current be 2. If what you actually want is test2, then do this:
var e = document.getElementById('dropdown');
var strUser = e.options[e.selectedIndex].text;
Which would make current be test2
Put the onChange="getSelectedValue" attribute of the select element and then use the following javascript.
<script>
function getSelectedValue(sel)
{
txtToFill.Text(sel.options[sel.selectedIndex].text);
}
</SCRIPT>
If I understand your question correctly you want to react to a combo box value changing and display different content in your page.
If that is the case what you need to know is
how to handle the change event in the select (drop down)
populate empty fields
Here's how you can register and handle the change event in the dropdown:
$("select[name='select']").on("change", function(){
$('#input1').val("What you want in the input goes here");
});
Here's a fiddle that demonstrates this.
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>