How to simplify multiple interactions with a textbox
Sometimes, you need to do multiple actions in a textbox as follows:
WebElement textbox = driver.findElement(textBoxId);
textbox.clear();
textbox.sendKeys("Java");
textbox.sendKeys(Keys.ENTER);
textbox.sendKeys(Keys.TAB);
This code finds the text box, clears the existing value, types a new value, presses ENTER, presses TAB.
5 lines of code.
Is it possible to simplify it?
First, create a class constant:
private static final String DELETE_KEY = Keys.chord(Keys.CONTROL,
"A",
Keys.DELETE);
Then, use a single sendKeys() command for all actions:
WebElement textbox = driver.findElement(textBoxId);
textbox.sendKeys(DELETE_KEY, "Java", Keys.ENTER, Keys.TAB);
Why does this work?
Because the parameter of sendKeys() has as type CharSequence... which means that it can get a variable number of parameters that have the CharSequence type:
void sendKeys(CharSequence... keysToSend);
CharSequence… is basically an array of Strings with a dynamic size.
The code can be simplified further .
First add a static import for the Keys enumeration:
import static org.openqa.selenium.Keys.*;
This allows use to remove the Keys enum name from the code:
WebElement textbox = driver.findElement(textBoxId);
element.sendKeys(DELETE_KEY, "Java", ENTER, TAB);
Thanks for reading.