WebElement interface provides isSelected method, which
return true if the element is currently selected or checked, false otherwise.
This operation only applies to input elements such as checkboxes, options in a
select and radio buttons.
<select>
<option
id="option1" value="Delhi">India</option>
<option
id="option2" value="Thimphu"
selected>Bhutan</option>
<option
id="option3" value="Maputo">Mozambique</option>
<option
id="option4" value="Wellington">New
Zealand</option>
<option
id="option5" value="Warsaw">Poland</option>
<option
id="option6" value="Helsinki">Finland</option>
</select>
isSelected method return true for the element with id
option2, for all other elements it return false.
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <div id="div1"> <h1 id="header1">Simple application to demonstrate Selenium webdriver</h1> </div> <select> <option id="option1" value="Delhi">India</option> <option id="option2" value="Thimphu" selected>Bhutan</option> <option id="option3" value="Maputo">Mozambique</option> <option id="option4" value="Wellington">New Zealand</option> <option id="option5" value="Warsaw">Poland</option> <option id="option6" value="Helsinki">Finland</option> </select> </body> </html>
Assume index.jsp is available at “http://localhost:8080/application”.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class App { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("http://localhost:8080/application"); WebElement ele1 = driver.findElement(By.id("option1")); WebElement ele2 = driver.findElement(By.id("option2")); WebElement ele3 = driver.findElement(By.id("option3")); WebElement ele4 = driver.findElement(By.id("option4")); WebElement ele5 = driver.findElement(By.id("option5")); WebElement ele6 = driver.findElement(By.id("option6")); System.out.println("is ele1 selected " + ele1.isSelected()); System.out.println("is ele2 selected " + ele2.isSelected()); System.out.println("is ele3 selected " + ele3.isSelected()); System.out.println("is ele4 selected " + ele4.isSelected()); System.out.println("is ele5 selected " + ele5.isSelected()); System.out.println("is ele6 selected " + ele6.isSelected()); driver.close(); } }
Output
is ele1 selected false is ele2 selected true is ele3 selected false is ele4 selected false is ele5 selected false is ele6 selected false
No comments:
Post a Comment