Saturday, June 21, 2014

How to Select Last value from the dropdown without using getOptions() ?

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class SelectLastOption
    {
    public static void main(String [] args) throws InterruptedException
    {
    WebDriver driver=new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("http://www.naukri.com/");
    driver.findElement(By.xpath("//li[p[text()='Job Category']]//span")).click();//click on job category dropdown
       
    List<WebElement> allOptions = driver.findElements(By.xpath("//select[@id='fareaSL']//option")); //get all the options from the dropdown
    System.out.println("last option is"+allOptions.get(allOptions.size()-1).getText()); //print last option
   
    Actions act = new Actions(driver);
    act.doubleClick(allOptions.get(allOptions.size()-1)).perform(); //its not always mandatory to use double click.
   
    //to confirm what value has been selected inside box
   
    String value = driver.findElement(By.xpath("//li[p[text()='Job Category']]//span/input")).getAttribute("value");
    System.out.println("the option has been selected is "+value);
}
}

No comments:

Post a Comment