I have to enter text in a input box in a selenium test in java. I am using below code to do that and it enters the characters but then deletes it:
WebElement depart=webControls.getDriver().findElement(By.id("oneWayFlight_fromLocation"));((JavascriptExecutor) webControls.getDriver()).executeScript("document.getElementById('oneWayFlight_fromLocation').value='JFK'");
OR
((JavascriptExecutor) webControls.getDriver()).executeScript("arguments[0].value='JFK';",depart);
OR
((JavascriptExecutor) webControls.getDriver()).executeScript(String.format("document.getElementById('oneWayFlight_fromLocation').value='JFK';","JFK"));
Here is the text field:
<input id="oneWayFlight_fromLocation" type="text" class="InputText-control hasError hasIcon" name="oneWayFlight_fromLocation" placeholder="From" autocomplete="off" value="">
I following setup:
To send a character sequence to the FROM and TO field using Selenium WebDriver you don't have to resort to JavascriptExecutor's executeScript()
method. Instead you can use the much proven and efficient sendKeys()
method inducing WebDriverWait for the elementToBeClickable()
and you can use either of the following Locator Strategies:
cssSelector
:
WebDriver driver = new InternetExplorerDriver();
driver.get("https://www.amextravel.com/flight-searches");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//li[text()='One Way']"))).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input#oneWayFlight_fromLocation"))).sendKeys("JFK");
xpath
:
WebDriver driver = new InternetExplorerDriver();
driver.get("https://www.amextravel.com/flight-searches");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//li[text()='One Way']"))).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='oneWayFlight_fromLocation']"))).sendKeys("JFK");
Browser Snapshot: