-
Notifications
You must be signed in to change notification settings - Fork 29
Browser: make selection in dropdown within a form
Martin Peter Madsen edited this page Jan 4, 2017
·
1 revision
Lets say you have a form that contains a dropdown and you want to make a selection in that dropdown based on the value of the option.
Example of From:
<html>
<form name="myFormName">
<select name="myDropdownMenu">
<option value="0">Select option</option>
<option value="OptionValue1">Option 1</option>
<option value="OptionValue2">Option 2</option>
<option value="OptionValue3">Option 3</option>
</select>
</form>
</html>
You will need a java script function to select a particular value, here is how:
//set your variables
$formUrl = "http://www.example.com/someForm";
$formName = "myFormName";
$ddName = "myDropdownMenu";
$ddOptVal = "OptionValue2";
$funcName = "selectForMe";
//execute
$localHostObj = \MTS\Factories::getDevices()->getLocalHost();
$windowObj = $localHostObj->getBrowser('phantomjs')->getNewWindow($formUrl);
$scriptData = "function ".$funcName."() {
//get the form element
var formEle = document.forms['".$formName."'];
if (typeof formEle != 'object') {
return 'Form with name: \'".$formName."\', does not exist';
}
//find the child dropdown element
var ddEle = formEle.elements['".$ddName."'];
if (typeof ddEle != 'object') {
return 'Dropdown with name \'".$ddName."\' in form: \'".$formName."\', does not exist';
}
//select the option you want
ddEle.querySelector(\"option[value='".$ddOptVal."']\").selected = true;
//did we succeed?
if (ddEle.value == '".$ddOptVal."') {
return 'Success';
} else {
return 'Failure';
}
}";
//load your script
$windowObj->loadJS($scriptData);
//execute the script
$funcReturn = $windowObj->callJSFunction($funcName);
//render a screenshot to show the dropdown has the desired value. In reallity you will check that
//$funcReturn == "Success", but for testing an image is more convincing.
echo '<img src="data:image/png;base64,' . base64_encode($windowObj->screenshot()) . '" />';
That is all.