Thursday, August 29, 2013

Select a Value from Drop Down Box



List options = driver.findElements(By.xpath(""));
          for (WebElement option : options) {
              if(option.getText().equals("value")){
                   option.click();
              }
          }
(OR)
Select list = new Select(driver.findElement(By.id("selection")));  
       list.selectByVisibleText("value");
(OR)
Select list = new Select(driver.findElement(By.id("selection")));  
       list.selectByIndex("value");
 
(OR)
Select the all options 

Select select = new Select(driver.findElement(By.tagName("select")));
     select.deselectAll();        select.selectByVisibleText("Text");// Based on text
     deselectByVisibleText("Text"); // Based on text
     select.selectByIndex(0); // Based on Index value
     selectByValue("Value"); // Based on Attribute Value
     deselectByValue("Value");// Based on Attribute Value
     isMultiple();// Returns TRUE if the drop-down element allows multiple selections at a time; FALSE if otherwise.
Ex:if( select.isMultiple()){
// Do some operation
}
          (OR)

Select select = new Select(driver.findElement(By.tagName("select")));
select.deselectAll();       
select.selectByText("Value");

                       (OR)
//Select element in multi select box in selenium webdriver

/**
* Select multiple options from a list box
*
* @param driver
* @param objectLocator
* @param values
* -Values by comma separated
* @throws Exception
 */
public void SelectMultiplesFromListBox(WebDriver driver, String values) throws Exception {

try {
if (values != "") {
Select sel = new Select(driver.findElement(By.id("someId"));
List options = sel.getOptions();
boolean isMultiple = sel.isMultiple();
Actions builder = new Actions(driver);
String data[] = values.split(",");
if (isMultiple) {
sel.deselectAll();
}
builder.keyDown(Keys.CONTROL);

// For loop to split and take single data from input data
for (String inputValue : data) {
System.out.println("Value From the inputlist is: " + inputValue);
// For loop to select a data from listbox
for (WebElement option : options) {
System.out.println("Total No of values in the listbox is : " + options.size());
String optionValue = option.getText().trim();
if (optionValue.equalsIgnoreCase(inputValue)) {
if (isMultiple) {
if (!option.isSelected()) {
builder.click(option);
}
}
break;
}
}
}
builder.keyUp(Keys.CONTROL).build().perform();

} else {
System.out.println("Please give some input data to select from the dropdown");
}
} catch (Exception e) {
}
}

 

No comments:

Post a Comment