How to select a value from dropdown with Selenium? - javascript

This is the source code :
<select name="backgroundcolor" onchange="backgroundColor();">
<option value="200">Red</option>
....
</select>
I tried below code in order to select the "Red" option but it didn't work.
Select dropDown = new Select(driver.findElement(By.name("backgroundcolor")));
dropDown.selectByValue("200");
I'm getting NoSuchElementException Exception
Unable to locate element //*[name='backgroundcolor']

try this
Select select = new Select(driver.findElement(By.name("backgroundcolor")));
select.deselectAll();
select.selectByVisibleText("Red");
perhaps the By.name is the problem, i am used to using something like :
By.xpath("//path_to_drop_down"))

try this, you need to convert the below code to the language you are using
from selenium.webdriver.support.select import Select as WebDriverSelect
element = WebDriverSelect(driver.find_element_by_name('backgroundcolor'))
element.select_by_value('200')

You note that it's possibly a timing issue. If so, you'll need to wait until the element appears on the page. Try this:
By locator = By.name("backgroundcolor");
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
Select dropDown = new Select(driver.findElement(locator));
dropDown.selectByValue("200");

I got " Unable to locate element *[name='backgroundcolor'] " error.I solved that problem when firstly I try to reach the iframe which contain that dropdown.It's a timing issue by the way.
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(theindexofframe));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("backgroundcolor")));
You should wait for the iframe to be loaded after that you should wait for the "backgroundcolor" element to be loaded also.After that you can select the value from dropdown like this:
Select dropDown = new Select(driver.findElement(By.name("backgroundcolor")));
dropDown.selectByValue("200");

Related

JS : .prepend() an option to 2 select doesn't work

I hope the title is self explanatory but i'll try to explain my problem nonetheless.
in my HTML file, i have 2 select, with no option. On the page load, a ajax request is performed to fetch some datas. In the success callback of my Ajax request, i create an option element for every data i just got. I also prepend those newly created option element to both of my select, but the only prepend that works is the one done on the last select
Here are SC of my code, in this examlple, the option have been prepended on the into_APPNAME select only, and not into the from_APPNAME. If i would revert the prepend such as
$("#into_" + repoName).prepend(option)
$("#from_" + repoName).prepend(option)
only from_APPNAME select would have got options in it.
Any ideas what's going on ?
You have to create two different HTML elements or clone the first one you created in order to create a new one. This code for example should populate both of them:
var option1 = $('<option></option>').attr('value', branch).text(branch);
var option2 = $('<option></option>').attr('value', branch).text(branch);
$("#into_" + repoName).prepend(option1);
$("#from_" + repoName).prepend(option2);
Of course better to clone the option1 into the option2
var option2 = $(option1).clone();
Another way can be the following, getting rid of variables:
$("#into_" + repoName).prepend($('<option></option>').attr('value', branch).text(branch));
$("#from_" + repoName).prepend($('<option></option>').attr('value', branch).text(branch));

Update some fields on change and on load

We have the following script which runs on a change to a drop-down - updates the price based on the currency code chosen. This basically gets the value of the drop-down and updates the priceamm and preicecurr fields within the text on the page.
<script>
function run() {
var f = document.getElementById("dropPrice");
priceamm.innerHTML = f.options[f.selectedIndex].value;
var e = document.getElementById("dropPrice");
pricecurr.innerHTML = e.options[e.selectedIndex].text;
}
HTML
<select id="dropPrice" onchange="run()" class="fa-select">
<option value = "a">aaa</option>
<option value = "b">bbb</option>
Question
Now, we would also like to load the drop-down to one of the options (selected) when loading the page (onload). We are able to populate the variables in the text but not the drop-down to show option bbb. In php this is quite easy but we are a bit lost with javascript. We tried something on these lines onload but does not work:
document.getElementById("dropPrice").value = "<?php echo $geo_price ;?>";
With jQuery this is probably easier but once again no luck:
window.onload = function() {
jQuery(document).ready(function($){
document.getElementById('dropPrice').find('option[value=<?php echo $geo_price ;?>]').attr('selected','selected');
});
}
Any help is appreciated. Thanks
The jQuery selector part is incorrect. You are mixing plain JS with jQuery. When you call document.getElementById('dropPrice') a regular DOM element is returned, but then you call find which is a jQuery method to be used on a jQuery element. So, you either need to wrap the first part to return a jQuery element like so:
$(document.getElementById('dropPrice'))
.find('option[value="b"]').attr('selected', true);
Or, select it via jQuery in the first place like:
$('#dropPrice [value="b"]');
However, your first example:
document.getElementById("dropPrice").value = "b";
should work. That makes me wonder if the value that is being echoed by PHP is correct and/or if there are other JS errors being thrown that would cause that code not to run.

selecting drop-down option of variable which contain html

A variable contains html
var empDaysStatusDropDown =
"<select class='statusList form-control'><option value='1'>Official On</option><option value='2'>Official Off</option><option value='3'>Sick Leave</option><option value='4'>Casual Leave</option><option value='5'>Annual Leave</option></select>"
I want to update this html through programming by selecting any of the dropdown option?
Means I want to select any of the option either 0,1,2,3 of dropdown and update html accordingly so that as I show that html on page the option will see selected which i select first
Try this
$(document.body).on("change",".statusList",function(){
if(".statusList option:selected").val()=="1"){
empDaysStatusDropDown ="new html";
}
})
Edit:
I have also created the fiddle for it : Demo
According to me you need to implement it before appending it to the page. So you want to manipulate it in jquery, Here we go:
var empDaysStatusDropDown =
$("<select class='statusList form-control'><option value='1'>Official On</option><option value='2'>Official Off</option><option value='3'>Sick Leave</option><option value='4'>Casual Leave</option><option value='5'>Annual Leave</option></select>");
empDaysStatusDropDown.find('option[value="1"]').attr('selected','selected');
// now you can append empDaysDropDown anywhere on the page.
$('body').append(empDaysStatusDropDown);
Hope this helps :)

create a new option and inject into select box using mootools 1.2

i have one AJAX function which return the list of countries. It works fine.
My problem is that want to load that countries in on select box which is already in HTML and is empty means no option value in it.
I want to know that how can i create a new option element and inject into the select box using moo tools 1.2
I have used below code but its not working in IE.
var NewOption = new Option("Select Sub Category",'0');
NewOption.inject($('nSub_nIndustryID'))
Thanks
Avinash
There is no need to create a variable, unless you are going to use it later.
new Element('option', {'value': 0, 'text':'Select states first'}).inject($('sCity'));
i have solved it my self..
var newElement = new Element('option');
newElement.inject($('sCity'));
newElement.setProperty('value','0');
newElement.appendText('Select States first');
Thx for your time....

Ajax problems in IE/Firefox

Hi I have an ajax script which validates the users information put into textboxes. This is working fine in Internet Explorer, but in FireFox I get an error in getting the gender from a listbox. I have got the gender to be placed into a hidden textbox, for easier processing. The error I get in FF is
dd is null
[Break on this error] theindex = dd.options[dd.selectedIndex].value;
My function in javascript is below, this is loaded on body load or once the gender selected is changed,
function get_gender()
{
{
var dd = document.getElementById("gender_select");
theindex = dd.options[dd.selectedIndex].value;
thevalue = dd.options[dd.selectedIndex].text;
}
document.getElementById("gender_text").value = thevalue;
}
One other problem I am having is hidding a div box, this works fine in every other browser but not IE. It should only show the div box once an error is given, but in IE the div box is always shown.
I am using this line to do this:
document.getElementById("username_div").style.visibility = "hidden";
Rather than pasting all my code the live page can be viewed at
http://elliottstocks.com/assignment/sign_up/
Ignore the login box, this works fine.
Any comments/help will be appreciated. Thanks alot =)
getElementByID requires the HTML element to have an ID, just a name isn't good enough.
<select name="gender_select" id="gender_select" onChange="get_gender()">
<option>Male</option> <option>Female</option>
</select>
For the null error change:
<select onchange="get_gender()" name="gender_select">
to
<select onchange="get_gender()" name="gender_select" id="gender_select">
document.getElementById is looking for an element in the DOM that has a given id attribute. The reason it works in IE is because it allows selecting by name attribute as well.
For your second problem, you may want to try display = 'none'; for your element. Be aware that this behavior is different from visibility = hidden.

Categories

Resources