Question

I'm having problems to get currently selected value of the select element. In some cases I can use:

element(by.css('#some-select')).$('[selected]').getText();

And it works just fine. But as I figured out it works only because selected attribute is present on option element. If I select option with javascript by setting select's value this way it's not possible to get element by selected attribute.

What is the proper way to get selected option or it's text because I can't find answer anywhere.

Thank you.

Was it helpful?

Solution

Ok, so right now I feel stupid and a little enraged at the same time.

It turns out that there is a simple way to get the option that is selected by simply calling:

element(by.selectedOption('model-name'));

Documentation here

I feel like this is a wrong way to do because instead of reusing element locator cache that I have defined (select element) I need to use new locator "selectedOption". It feels bad because naturally I would like to simply call something like element(by.css('#some-select')).getSelected();

But maybe there is a way that I could not just find?

OTHER TIPS

So I just ran into this, and I couldn't find any answer that I really liked..

My Answer

First, I recommend changing the ng-options by adding track by statement.

for example:

<select ng-options="l.id as ('filters.languages.' + l.id | translate) for l in limitedLanguages track by l.id" ng-model="filterLanguage">
</select>

This will add the id on the option element so instead of getting

<select ng-options="l.id as ('filters.languages.' + l.id | translate) for l in languages" ng-model="filterLanguage" class="ng-pristine ng-valid ng-touched">
    <option value="0">All</option>
    <option value="1" selected="selected">English</option>
    <option value="2">Hebrew</option>
    <option value="3">Russian</option>
    <option value="4">Arabic</option>
    <option value="5">Other</option>
</select>

you get

<select ng-options="l.id as ('filters.languages.' + l.id | translate) for l in languages track by l.id" ng-model="filterLanguage" class="ng-valid ng-dirty ng-valid-parse ng-touched">
    <option value="all" selected="selected">All</option>
    <option value="english">English</option>
    <option value="hebrew">Hebrew</option>
    <option value="russian">Russian</option>
    <option value="arabic">Arabic</option>
    <option value="other">Other</option>
</select>

note that without the track by the value is simply the index (0,1,..) and with the track by the value is more readable/meaningful (all,english,...)

then you can use getAttribute on value to get the value as mentioned in other answers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top