13
Dec

Select a dropdown value via Javascript

For HTML page with Select element as follow:

<html>
<body>
<select id="type" class="text-input ng-pristine ng-valid ng-scope ng-touched" ng-style="cssStyle" name="typedd" ng-if="!options.hidePlaceholder" ng-model="result.type" qmx-observe-value="text" ng-disabled="options.readonly" ng-options="obj.value as obj.text group by obj.groupby for obj in selectData" style="font-size: 13px; opacity: 1; width: 100%;">
    <option class="ng-binding" value="">----</option>
    <option value="0" selected="selected" label="Text">Text</option>
    <option value="1" label="Date">Date</option>
    <option value="2" label="Numeric">Numeric</option>
    <option value="3" label="Switch">Switch</option>
    <option value="4" label="Map Location Marker">Map Location Marker</option>
    <option value="5" label="Picker">Picker</option>
    <option value="6" label="List">List</option>
    </select>
</body>

</html>
		System.setProperty("webdriver.chrome.driver", "C:\\Browserdrivers_Selenium\\chromedriver.exe");
		WebDriver driver = new ChromeDriver();
		
		driver.get("file://C:\\Users\\srasz\\Desktop\\abc.html");
		
		WebElement select = driver.findElement(By.name("typedd"));
		
((JavascriptExecutor)driver).executeScript("var select = arguments[0];"+
  "for(var i = 0; i < select.options.length; i++) "+
   "{"+
	"if(select.options[i].text == arguments[1])"+
	"{"+
		"select.options[i].selected = true; "+
	 "}"+
    "}", select, "Date");
		
		Thread.sleep(20000);

		driver.quit();