Selenium WebDriver-Working with Listbox and Multi-Select Listbox


We are going to see how to retrieve values of Single Select List box and How to Select multiple options in different ways on a Multi Select Listbox.






















import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class Listboxes {

WebDriver driver=new FirefoxDriver();
  @Test
  public void Listboxtest() throws InterruptedException {

 driver.get("http://gwt.googleusercontent.com/samples/Showcase/Showcase.html#!CwListBox");

 driver.manage().window().maximize();

 Thread.sleep(5000);

//1. Single select list box -->first value will be the default value of the dropbox
 WebElement lbox=driver.findElement(By.id("gwt-debug-cwListBox-dropBox"));
 List<WebElement> values=lbox.findElements(By.tagName("option"));


 for( WebElement val : values)
 {
 System.out.println(val.getText().toString());//Prints the values of the Listbox
 }



 //2. Multi Select list box -->a) Selecting a particular option 
 
 WebElement lbox1=driver.findElement(By.id("gwt-debug-cwListBox-multiBox"));

lbox1.sendKeys("c"); //One More method of selecting a value in listbox is to just type the 
       //the first character of the value in the listbox.So now,in this example the first value //"compact" will be selected.

 //2b)select multiple options in the multi box by clicking control key
String selectAll = Keys.chord(Keys.CONTROL, Keys.SHIFT,Keys.ARROW_DOWN);
lbox1.findElement(By.tagName("option")).sendKeys(selectAll);

 //2c)This is the usual way of selecting value

  List<WebElement> values1=lbox1.findElements(By.tagName("option"));
 for( WebElement val : values1)
 {
 System.out.println(val.getText());

 if (val.getText().toString().equalsIgnoreCase("coupe"))
 {
 val.click();
 }
  else if(val.getText().equalsIgnoreCase("truck"))
 {
 val.sendKeys(Keys.CONTROL);
 val.click();
 }

  }



  driver.close();
 driver.quit();

  }
}
The Usage of Keys and Chord is explained in my previous blogpost.

Comments

Popular posts from this blog

Cypress Cheat Sheet

Selenium WebDriver -Handling JavaScript alerts