How To Deselect Option By Visible Text Or Value Or By Index In Selenium WebDriver With Example

Adding selection or removing selection from list box are very common actions for list box. Selenium WebDriver has 3 alternate options to select or deselect value from list box. It is very important to learn all three methods of selecting or deselecting option from list box because if one is not possible to implement in your test then you must be aware about alternate option. I already described 3 selection options in my earlier posts - Selecting specific option BY VISIBLE TEXT, BY VALUE or BY INDEX  from drop down or list box.

Now let me describe you all three deselect methods to deselect specific option from list box. Do you remember that we can use "removeSelection" command to deselect option from list box? VIEW THIS SELENIUM IDE EXAMPLE for "removeSelection" command.

1. Deselect By Visible Text
If you wants to remove selection from list box then you can use webdriver's deselectByVisibleText() method. Syntax is as bellow. 1st syntax will locate the select box and 2nd syntax will remove selection by visible text = Russia.
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByVisibleText("Russia");

2. Deselect By Value
You can also deselect option from list box by value. 2nd syntax will deselect option by value = Mexico.
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByValue("Mexico");

3. Deselect By Index
Bellow given syntax will remove selection by index = 5.
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByIndex(5);

Execute bellow given example in eclipse and observe results during execution.

Copy bellow given @Test method part of deselect option by visible text or value or index and replace it with the @Test method part of example given on THIS PAGE.(Note : @Test method is marked with pink color in that linked page).


@Test
 public void test () throws InterruptedException 
 {  
  driver.findElement(By.id("text1")).sendKeys("My First Name");

  Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
  listbox.selectByVisibleText("USA");
  listbox.selectByVisibleText("Russia");
  Thread.sleep(1000);
  
//To deselect by visible text
  listbox.deselectByVisibleText("Russia");
  Thread.sleep(1000);
  
  listbox.selectByValue("Japan");
  listbox.selectByValue("Mexico");
  Thread.sleep(1000);
  
//To deselect by value
  listbox.deselectByValue("Mexico");
  Thread.sleep(1000);
  
  listbox.selectByIndex(4);
  listbox.selectByIndex(5);
  Thread.sleep(1000);
  
//To deselect by index
  listbox.deselectByIndex(5);
  Thread.sleep(1000);

  driver.findElement(By.xpath("//input[@value='->']")).click();
  Thread.sleep(1000);
 }   
}

You can view MORE webdriver examples on THIS LINK.

No comments:

Post a Comment