Articles → SELENIUM → Working With Multiselect Listbox In Selenium

Working With Multiselect Listbox In Selenium






Create A Multi-Select List Box




<!DOCTYPE html>
<html lang="en"
	xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>
	<body>
		<select id="AllOptions" multiple="">
			<option value="1"  selected>Option 1</option>
			<option value="2">Option 2</option>
			<option value="3" selected>Option 3</option>
			<option value="4">Option 4</option>
		</select>
	</body>
</html>




Picture showing the sample html multiselect listbox
Click to Enlarge


Methods Of Multiselect List Box In Selenium




  1. isMultiple – Method to check if the list box is multiselect or not.
  2. getAllSelectedOptions – Method to get the list of selected options in list box.

Code


package com.FirstSeleniumProject;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class MyClass {
  @Test
	public void TestAnnotation() {
		WebDriver driver;
		String service = "IEDriverServer path";
		System.setProperty("webdriver.ie.driver", service);
		driver = new InternetExplorerDriver();
		driver.get("http://localhost:18275/Page1.html");

		Select selectObject = new Select(driver.findElement(By.id("AllOptions")));
		// Checking if list box is multiselect or not
		System.out.println(selectObject.isMultiple());

		List < WebElement > selected = selectObject.getAllSelectedOptions();

		for (WebElement element: selected) {
			System.out.println(element.getText());
		}
	}
}



Output


Picture showing the output of working with multiselect listbox in Selenium
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, May 4, 2017

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250