Reputation: 430
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:
Upvotes: 1
Views: 116
Reputation: 193088
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:
Upvotes: 1
Reputation: 11335
I suggest trying to make a test with Sendkeys(). I try to test it on my side and it works without any issue.
public static void main(String[] args) {
System.setProperty("webdriver.ie.driver","D:\\D drive backup\\selenium web drivers\\IEDriverServer.exe");
WebDriver browser = new InternetExplorerDriver();
browser.get("https://www.amextravel.com/flight-searches");
browser.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
WebElement txtbox1=browser.findElement(By.name("oneWayFlight_fromLocation"));
txtbox1.sendKeys("ABC");
WebElement txtbox2 = browser.findElement(By.name("oneWayFlight_toLocation"));
txtbox2.sendKeys("xyz");
}
Output:
Further, you can modify the code to work as per your requirements.
Upvotes: 0