Select Radio Button in a group using Selenium WebDriver with Java - java

I want to be able to select a radio button within a group (of radio buttons) identified by the name attribute:
<div>
<input type="radio" name="exampleInputRadio" id="optionRadio1" value="1">
<input type="radio" name="exampleInputRadio" id="optionRadio2" value="2">
<input type="radio" name="exampleInputRadio" id="optionRadio3" value="3">
<input type="radio" name="exampleInputRadio" id="optionRadio4" value="4">
</div>
I use the following code to do what I want:
public void exampleInputRadio(WebDriver driver, int option) {
List<WebElement> radios = driver.findElements(By.name("exampleInputRadio"));
if (option > 0 && option <= radios.size()) {
radios.get(option - 1).click();
} else {
throw new NotFoundException("option " + option + " not found");
}
}
The problem is that Selenium always selects the first radio button, no matter the value of option argument is.
And when I code this in the above method:
for (int i = 0; i < radios.size(); i++) {
System.out.println(radios.get(i).getAttribute("id"));
}
I get this output:
optionRadio1
optionRadio2
optionRadio3
optionRadio4

The code is absolutely working fine for me on Firefox 28.
I have tried something like this:
function:
public void exampleInputRadio(WebDriver driver, int option) {
List<WebElement> radios = driver.findElements(By.name("exampleInputRadio"));
if (option > 0 && option <= radios.size()) {
radios.get(option - 1).click();
} else {
throw new NotFoundException("option " + option + " not found");
}
}
functions called:
TestClass tc = new TestClass();
tc.exampleInputRadio(driver, 1);
tc.exampleInputRadio(driver, 2);
tc.exampleInputRadio(driver, 3);
tc.exampleInputRadio(driver, 4);

A simple work around could be using the value or the id attributed.
driver.findElement(By.id("optionRadio" + (option + 1))).click();

Also you can use xpath, something like this:
driver.findElement(By.xpath("//input[#value='1]")).click();

Related

How to pass dynamically added textbox to spring MVC controller java

$("#addButton").click(function () {
if(counter > 3){
alert("Only 3 textboxes allowed");
return false;
}
var selectfield = $('#selectcolumnlist option:selected').val();
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv');
newTextBoxDiv.after().html('<input type="text" name="textbox_' + selectfield + '" class="form-control" id="textbox_'+selectfield+'" placeholder="' + selectfield + '" value="" style="width: 400px;"/><input type="button" value="Remove Field" class="remove_this" id="removeid" accessKey="'+selectfield+'"/>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
$('#selectcolumnlist option:selected').remove();
counter++;
});
$("#TextBoxesGroup").on('click', '#removeid', (function() {
var a = $(this).attr('accessKey');
alert(a);
$(this).parent('div').remove();
$('#selectcolumnlist').append(new Option(a,a));
counter--;
}));
Above code is adding a textbox based on the dropdown select option. It can add a maximum of 3 textboxes.
How do I pass this textbox value to spring MVC controller.
It appears that you are using JQuery to build the UI. Assuming that you have a Spring MVC endpoint exposed at POST http://localhost:8080/api/boxes you can use jQuery.ajax() method:
$.ajax({
method: "POST",
url: "http://localhost:8080/api/boxes",
data: { textbox: "value" }
})
.done(function(msg) {
alert("Saved: " + msg);
});

Unable to check state of elements

I am trying to automate for my first time a complete flow for a e-comm app. After Add to cart button is clicked, a quantity spinner is displayed instead of that button, with "+" and "-" buttons. I am trying to determine if the button was clicked. If so, click on "-" button and then click again on Add to Cart button for that element and move to next button and so on. This is what I have done so for, but without any luck:
private static void addProductsToCart()
{
List<WebElement> buttons = driver.findElements(By.className("actions__addToCart"));
WebElement action = driver.findElement(By.xpath("//*[#id=\"content\"]/div/section/ul/div/div/li/div/div/div/div/div/button[1]"));
for(int i = 0; i <= buttons.size(); i++)
{
if(action != null && action.isDisplayed())
{
action.click();
}
buttons.get(i).click();
if(i == 4)
{
break;
}
}
}
Any help would be much appreciated.
<div class="quantitySpinner alignmentContainer__element" data-bind="visible: size().quantity() > 0" style="">
<button class="decrease" data-bind="click: decrementQuantity, attr: {'aria-label': ogs.gsa.resources.Accessibility_DecreaseQuantity.formatWith({productBrand: model.Brand, productName: model.Name})}" aria-label="Subtract One Birds Eye Steamfresh Chef's Favorites Rotini & Vegetables"></button>
<label data-bind="text: size().quantity, attr:{'aria-live':'polite', 'aria-atomic':'true'} " aria-live="polite" aria-atomic="true">1</label>
<button class="increase" data-bind="click: incrementQuantity, attr: {'aria-label': ogs.gsa.resources.Accessibility_IncreaseQuantity.formatWith({productBrand: model.Brand, productName: model.Name})}" aria-label="Add One Birds Eye Steamfresh Chef's Favorites Rotini & Vegetables"></button>
</div>
For clicking on decrease button, you can try this code :
WebDriverWait wait = new WebDriverWait(driver , 20);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.decrease"))).click();
As you have mentioned, that you want to click on click again on Add to Cart button
for that :
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath of add to cart button
or any other locator as per your convenience ")))

Selenium Apply button not working on combo box?

I have problem with apply button. I have combo box filter and everything is fine, it is switching between squares.But when it suppose to do apply, somehow it just continue like it is not selected anything and test finishes successfully, but there is no filtering that I need.
Can someone check my code and part with inspector bug. Maybe I am missing something?
My Java code:
if (type.equals("")) {
elementList = driver.findElements(By.xpath("//div[#id='" + id + "_menu']//a[#class='FIText']"));
if (elementList.size() > 0) {
if (driver.findElements(By.xpath("//div[#id='" + id + "_menu']//div[#class='CFApplyButtonContainer']//button[#class='tab-button']//span[#class='label'][text()='Apply']/..")).size() > 0) {
type = "multi_checkbox_with_apply";
}else {
type = "multi_checkbox_without_apply";
}
}
}
Inspector bug:
<div class="CFApplyButtonConatiner" style="height: 21px;">
<button class="tab-button tab-widget disabled" type="button" style="max-width: 56px" disabled="">
<span class="icon"></span>
<span class="label">Cancel</span>
</button>
<button class="tab-button tab-widget focus disabled" type="button" style="max-width: 56px" disabled="">
<span class="icon"></span>
<span class="label">Apply</span>
</button>
Can someone check this please?
I don't have idea why it is not working? Maybe someone has idea how to test it.
BR,
Marija
Just to be clear, this solution will look for element which is displayed and it will click on it!!
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.CFApplyButtonConatiner"))));
List<WebElement> elementsList = driver.findElements(By.cssSelector("div.CFApplyButtonConatiner > button");
for(WebElement ele: elementsList) {
if(ele.isDisplayed()) {
ele.click();
}
}
I have used like Ranijth's suggestion:
if (type.equals("")) {
elementList = driver.findElements(By.xpath("//div[#id='" + id + "_menu']//a[#class='FIText']"));
if (elementList.size() > 0) {
//if (driver.findElements(By.xpath("//div[#id='" + id + "_menu']//div[#class='CFApplyButtonContainer']//button[#class='tab-button']//span[#class='label'][text()='Apply']/..")).size() > 0) {
if (driver.findElements(By.cssSelector("div.CFApplyButtonConatiner > button"))!=null) {
//if (driver.findElements(By.cssSelector("div.CFApplyButtonConatiner > button")).size() > 0) {
type = "multi_checkbox_with_apply";
}
else {
type = "multi_checkbox_without_apply";
}
}
}
And now it is working fine, but now I need to test it to check output. If someone have better solution, let me know.

How to verify the button having drop down menu using selenium in java

There is a button. When you click on this button, a drop down menu having two option appears. How to verify this scenario using selenium in java.
<div class="hpDropDownButton">
<button class="button ng-binding">Holidays Operation</button>
<ul>
<li>
<a class="ng-binding" ng-click="uploadHolidays()">Upload Holidays</a>
</li>
<li>
<a class="ng-binding" ng-click="deleteHolidays()">Delete Holidays</a>
</li>
</ul>
Click on the button
Now :-
Boolean dropdownPresent = driver.findElement("YOUR LOCATOR OF DROPDOWN").isDisplayed();
if(dropdownPresent==true)
{
System.out.println("Dropdown is appearing");
}
else{
System.out.println("Dropdown is not appearing");
}
Hope it will help you :)
You are asking to verify whole scenario. You need to first understand what Selenium-WebDriver is. Refer this tutorial for more explanation.
However you can follow below code,
WebDriver driver = new FirefoxDriver();
String appUrl = "your url";
driver.get(appUrl);
// maximize the browser window
driver.manage().window().maximize();
// upto code from your button
WebElement button_element = driver.findElement(button_locator);
button_element.click();
// to verify a drop down menu having two option appears
boolean flag = isPresent(dropdown_locator);
if (flag) {
// code bases on dropdown displayed
}
else {
// code bases on dropdown not displayed
}
To verify if element is present or not use this method
public boolean isPresent(String locator) {
return findElements(locator).size() > 0 ? true : false;
}
First of all collect all the Drop down values in List, List values = Upload Holidays#Delete Holidays
Then click on Dropdown WebElement, by using DropdownFieldName = driver.findElement(by.xpath(//button[#class='button ng-binding'])).click();
Take the couunt of dropdown values, by drptotalCount = driver.findElements(by.xpath(//a[#class='button ng-binding']));
Now you have expected DropDown values and count of Dropdown Values.
You can take a reference from below code:
checkDropDownValues(String DropdownFieldName, String values){
driver.findElement(By.xath(DropdownFieldName)).click();
WebElement drptotalCount = driver.findElements(by.xpath(//a[#class='button ng-binding']));
int numberOfDropDown = drptotalCount.size();
List<String> allDropDownValues = Arrays.asList(values.split("#"));
for (int colCount = 1; colCount <= numberOfDropDown; colCount++) {
boolean flag = false;
Actualvalue = driver.findElement(By.xpath(drptotalCount + "[.=" + allDropDownValues.get(colCount) +"]"])).getText();
String expectedValues = allDropDownValues.get(colCount);
if(expectedValues.equalIgnoreCase(Actualvalue))
{
flag = true;
}
Assert.assertTrue("Column values doesn't match", flag);
}
}
Click the button (which should be straight forward)
it seems you have some asynchronous call or a delay
Wait for the drop-down 'div.hpDropDownButton' is beeing displayed using WebDriverWait:
WebElement myDynamicDropDown = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.CssSelector("div.myDynamicDropDown")))
continue ..
http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp

How to clik on a text in the div

Could any one please help me in selecting the text (en_GW) under a div?
<-div class="x-combo-list-inner" id="cq-gen339" style="width: 253px; height: 300px;">
<-div class="x-combo-list-item x-combo-selected" ext:qtip="">en_GW<-/div><-div>
Note: Below code not working:
driver.findElement(By.className("x-combo-list-item x-combo-selected")).click();
Error
Compound class names are not supported. Consider searching for one class name and filtering the results.
// xpath
driver.findElement(By.xpath("//div[contains(#class, 'x-combo-list-item x-combo-selected')]")).click();
// css selector
driver.findElement(By.cssSelector("div.x-combo-list-item.x-combo-selected")).click();
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
$(txt5).clickToggle(function() {
alert('First handler: ' + $(this).text());
}, function() {
alert('Second handler: ' + $(this).text());
});
i have no of elements if clicking div count will increase. at the same time click other div first will count will be 0 ?

Categories

Resources