Reputation: 75
Select dropdown1 = new Select(driver.findElement(By.xpath("//html/body/div/div[2]/div/div/div//div//select")));
List<WebElement> drop1 = dropdown1.getAllSelectedOptions();
for(WebElement temp : drop1) {
String drop_text = temp.getText();
System.out.println(drop_text);
}
The above xpath represents 3 dropdown fields.When i execute this code i am getting the selected text in first dropdown only.What changes i need to do in this to get the selected options from all three dropdown fields.
**html code**
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="type-select">Category<span style="color:red">*</span></label>
<div class="col-md-8 col-sm-8">
<select defaultattr="4" class="form-control input-style mandatory" data-val="true" data-val-number="The field CategoryID must be a number." id="CategoryID" name="CategoryID"><option value="">--Select--</option>
<option value="1">Architectural Firm</option>
<option value="2">Interior Design Firm</option>
<option value="3">General Contractor</option>
<option selected="selected" value="4">2tec2 Sales Network</option>
<option value="5">Cleaning Company</option>
<option value="6">Commercial end user</option>
</select>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="type-select">Company Status</label>
<div class="col-md-8 col-sm-8">
<select class="form-control input-style" id="ddlCompanyStatus">
<option selected="selected" value="1">Active</option>
<option value="0">Non Active</option>
</select>
</div>
</div>
<div class="form-group">
Upvotes: 0
Views: 134
Reputation: 13712
You can use css selector option:checked
to get selected options
List<WebElement> selectedOpts = driver.findElements(
By.cssSelector("select.form-control > option:checked"));
for(WebElement temp : selectedOpts ) {
System.out.println(temp.getText());
}
Upvotes: 1
Reputation: 83527
First of all, calling findElement()
only returns a single element from the HTML page. In order to get all elements that match a given selector, you need to call findElements()
instead.
Secondly, you seem to be under the impression that getAllSelectedOptions()
will return all of the options selected for all <select>
fields. This is not the case. Instead, it only returns all of the selected options for a single <select>
field. This only makes sense if you use the multiple
attribute.
To get the selected option in each <select>
, you first need to use findElements()
instead of findElement()
. Then you need to iterate over the selected elements and call getSelectedOption()
on each one.
Upvotes: 1