Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get option value of select element

I am trying to get the option value of a select element using Protractor. However, I'm not able to find the option element.

HTML

<select ng-options="opions.c as options.n for option in options" ng-model="model">
    <option value="0">Option 1</option>
    <option value="1">Option 2</option>
</select>

Spec-file

describe('testing select option', function() {
    it('', function() {
        ptor = protractor.getInstance();

        //This will not get the option required
        ptor.findElement(protractor.By.binding('model'));
    });
});

I cannot seem to find a way to grab the option value as I haven't found a function that I can use that doesn't give and exception or error message.

Does anyone know how to resolve this issue?

like image 529
Ian Richards Avatar asked Aug 23 '13 11:08

Ian Richards


People also ask

How can check select option value is selected or not in jQuery?

$('#mySelectBox option'). each(function() { if ($(this). isChecked()) alert('this option is selected'); else alert('this is not'); });


1 Answers

I have had some problems getting dropdowns working well, and have spent some time today working it out (and therefore I'm sharing it here in case someone else finds it useful).

On earlier versions of Protractor there was a by.selectedOption, which effectively does the same thing as by.select, but returns only the selected item. So, to get the text of the selected option above, you could have:

expect(element(by.selectedOption('model')).getText()).toEqual('Option 1');

I wrote a blog post if you want more detail, it also covers a helper function for selecting the option in the dropdown: http://technpol.wordpress.com/2013/12/01/protractor-and-dropdowns-validation/

Recent versions of protractor have removed this function, replacing it with:

expect(element(by.id('my_id')).element(by.css('option:checked')).getText();

Which is more flexible, as it can be applied to any of the finders, whereas selectedOption only worked with a model finder.

like image 130
PaulL Avatar answered Sep 18 '22 11:09

PaulL