How to get selected option value in protractor

倾然丶 夕夏残阳落幕 提交于 2019-12-08 03:57:14

问题


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.


回答1:


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




回答2:


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:

  • Select -> option abstraction


来源:https://stackoverflow.com/questions/47588304/how-to-get-selected-option-value-in-protractor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!