1

How can I get currently selected option value of selectbox?

I have tried below code but it's not working.

element(by.css('#selectbox')).all(by.tagName('option')).then(function (options) {
    options.forEach(option => {
        if (option.getAttribute('selected')) {
            console.log('selected option', option);
        }
    });
});

Any help would be appreciated.

Pratik Gadoya
  • 1,420
  • 1
  • 16
  • 27
  • 1
    Possible duplicate of [How to get option value of select element](https://stackoverflow.com/questions/18401812/how-to-get-option-value-of-select-element) – Sudharsan Selvaraj Dec 01 '17 at 11:00

2 Answers2

2

Is "selected" and attribute or a class-value?

It would work as "get element, which is selected, then read out its value"

In code:

//if selected is an attribute
element(by.css('#selectbox option[selected]')).getAttribute('value').then(function(value){
    console.log('selected option is '+value);
})

//if selected is a class-attribute
element(by.css('#selectbox option.selected')).getAttribute('value').then(function(value){
    console.log('selected option is '+value);
})

//note, that "element(by.css())" === "$()", so this is the same as the first one
$('#selectbox option[selected]').getAttribute('value').then(function(value){
    console.log('selected option is '+value);
})

Read more here about locators and even more important here about CSS-Selectors

Ernst Zwingli
  • 1,402
  • 1
  • 8
  • 24
0

You can either use .filter() to filter out the selected option, or target it directly with a CSS selector:

element(by.css('#selectbox option[selected]'))

Note that there is an overall nicer way to deal/interact with the select in Protractor:

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195