Reputation: 3272
How to loop through all the label
items in a div
. I mean there are a bunch of unknown number of label tags which inturn have radio button. Using Selenium WebDriver. I need to find the selected radio button
. There are two things here:
For example
<div class="controls">
<label class="radio inline">
<input type="radio" value="0" name="PlaceOfResidence"/>
Urban
</label>
<label class="radio inline">
<input type="radio" value="1" name="PlaceOfResidence"/>
Suburb
</label>
<label class="radio inline">
<input type="radio" value="2" name="PlaceOfResidence"/>
Rural
</label>
<label class="radio inline">
<input type="radio" value="3" name="PlaceOfResidence"/>
Not Available
</label>
</div>
Here is what I've tried
private String isRadioButtonSelected2(String name){
List<WebElement> webEl = this.getWrappedDriver().findElements(By.xpath("//input[@type='radio' and @name = '"+name+"']/parent::label")); //and @value='"+value+"']"));
String selectedValue = "";
for(WebElement element: webEl){
Boolean selectedRadio = element.isSelected();
if(selectedRadio){
selectedValue =this.getWrappedDriver().findElement(By.xpath("//input[@type='radio' and @name = '"+name+"']/parent::label")).getText();
log("&&&&&&&&&&"+selectedValue);
}else{
return null;
}
}
return selectedValue;
}
Upvotes: 0
Views: 4306
Reputation: 23825
Instead of using xpath
to find all radio buttons you can find it just simply using By.name
which is much faster than xpath
. Try as below :-
List<WebElement> radioButtons = this.getWrappedDriver().findElements(By.name("PlaceOfResidence"));
int size = radioButtons.size();
// This is the count of total radio button
for(WebElement radio : radioButtons)
{
If(radio.isSelected())
{
String selectedValue =radio.findElement(By.xpath("./parent::label")).getText();
}
}
Hope it helps...:)
Upvotes: 3
Reputation: 628
//This will give the number of radio elements
List<WebElement> radioButtons = driver.findElements(By.xpath("//input[type=radio]"));
int size = = radioButtons.size();
// Iterate the above element and use isSelected() method to identify the selected radio elements
Hope this clarify
Upvotes: 1