Reputation: 915
I'm trying to return the options present in the list using the below function.
HTML
<select>
<option>one</option>
<option>two</option>
<option>three</option>
<select>
Function
getValues(){
var ele = element(by.xpath("......../select"));
return ele.all(by.tagName('option')).getAttribute('value').getText().then(function (text){
for (var i = 0; i < text.length; i++) {
text[i] = text[i].trim();
}
return text;
});
}
When I print the values in console using console.log(getValues())
, the console displays theManagedPromise{.....}
function instead of options.
But I'm expecting the options as ["one","two","three"]
array. Can anyone help me?
Upvotes: 0
Views: 2413
Reputation: 2375
Why create a complex method for it if you can also do it like this
getValues() {
return element.all(by.css('select option')).getText();
}
The getText()
can also be executed on a ElementFinderArray and it will return a promise that contains ['one', 'two', 'three']
Update: with trim function
First of all your code will not work because of 2 reasons:
.getAttribute('value').getText()
. This will never work.Below you will find a working example in 3 different styles.
// with your code
getValues() {
var ele = element(by.xpath("......../select"));
return ele.all(by.tagName('option'))
.map(function(option) {
return option.getText()
.then(function(optionText) {
return optionText.trim();
});
});
}
// with protractor shorthand notation
getValues() {
return $$('select option').map((option) => {
return option.getText()
.then((optionText) => {
return optionText.trim();
});
});
}
// 1 line
getValues() {
return $$('select option').map((option) => option.getText().then((optionText) => optionText.trim()));
}
Upvotes: 1
Reputation: 8904
<!DOCTYPE html>
<html>
<body>
<select id="sel">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<p>Click the button to display values</p>
<button onclick="clickHandler()">Try it</button>
<p id="demo"></p>
</body>
<script "text/javacript">
function clickHandler() {
var options = document.getElementById("sel").childNodes;
let results =[];
[].forEach.call(options, function(option) {
if (option instanceof HTMLOptionElement) {
results.push(option.text);
// Swap for option.value if you like too would be lower case
}
});
document.getElementById("demo").innerHTML = results.toString();
}
</script>
</html>
See live demo here
HTMLOptionElement on MDN
Upvotes: 0
Reputation: 1199
The most elegant way is to use .map()
.
See the documentation.
The only thing you need to remember is that .map()
returns A promise that resolves to an array of values returned by the map function.
Upvotes: 0