Search code examples
c#htmlseleniumselenium-webdriverhtml-datalist

How to select from a HTML5 datalist with Selenium


I'm trying to select from a datalist but only the first element in the list seems to be selectable.

This is a HTML snippet:

<td>
<input id="applianceFilterTextbox" class="flat" name="applianceFilter" list="applianceNames" value="ROC-1006 - B827EBB5D539" style="width: 100%"/>
<datalist id="applianceNames">
<!-- ngRepeat: app in appliances -->
<option class="ng-binding ng-scope" ng-repeat="app in appliances" value="ROC-1006 - B827EBB5D539" ng-value="app.DisplayName">ROC-1006 - B827EBB5D539</option>
<!-- end ngRepeat: app in appliances -->
<option class="ng-binding ng-scope" ng-repeat="app in appliances" value="ROC-1007 - B827EBD15125" ng-value="app.DisplayName">ROC-1007 - B827EBD15125</option>
<!-- end ngRepeat: app in appliances -->
<option class="ng-binding ng-scope" ng-repeat="app in appliances" value="ROC-1008 - B827EB05DEF3" ng-value="app.DisplayName">ROC-1008 - B827EB05DEF3</option>
<!-- end ngRepeat: app in appliances -->
<option class="ng-binding ng-scope" ng-repeat="app in appliances" value="ROC-1009 - B827EB2A379C" ng-value="app.DisplayName">ROC-1009 - B827EB2A379C</option>
<!-- end ngRepeat: app in appliances -->
</datalist>
</td>

My module is as follows:

public void SelectApplianceFromDatalist(int index)
{
    ExplicitWait.waitElementToBeClickable(driver, 25, appliancesFilterTextBox);
    appliancesFilterTextBox.Clear();
    appliancesFilterTextBox.Click();
    string select1 = driver.FindElement(By.XPath("//*[@id='applianceNames']/option['" + index + "']")).GetAttribute("value");
    index++;
    string select2 = driver.FindElement(By.XPath("//*[@id='applianceNames']/option['" + index + "']")).GetAttribute("value");
    index++;
    string select3 = driver.FindElement(By.XPath("//*[@id='applianceNames']/option['" + index + "']")).GetAttribute("value");
    index++;
    string select4 = driver.FindElement(By.XPath("//*[@id='applianceNames']/option['" + index + "']")).GetAttribute("value");

    appliancesFilterTextBox.SendKeys(driver.FindElement(By.XPath("//*[@id='applianceNames']/option['"+ index +"']")).GetAttribute("value"));
}

The select1,select2,select3 and select4 are only present for debug purposes. When calling the module with a value of for instance 3 for index they all contain the value of the first option.


Solution

  • Try the simple method sendKeys() to send your required value like -

        driver.findElement(By.id("applianceFilterTextbox")).clear();
        driver.findElement(By.id("applianceFilterTextbox")).sendKeys("ROC-1008 - B827EB05DEF3");
    

    It will clear the default selected value and enter your required value.

    Other thing is that I think you are using right approch but there is minor mistake in your XPath. Do change

    By.XPath("//*[@id='applianceNames']/option['" + index + "']") 
    

    to

    By.XPath("//*[@id='applianceNames']/option["+ index +"]")