TesterABC
TesterABC

Reputation: 1226

Select a particular option in Protractor

I'm a new born QA and I'm trying here to write a Protractor script to select an option from a dropdown. There are 2 options in my dropdown and I'm trying to select it from number.

Here is the code I'm using.

var selectDropdownbyNum = function ( element, optionNum ) {
    if (optionNum){
    var options = element.findElements(by.tagName('entity.company_id as entity.company_name for entity in entities'))   
      .then(function(options){
        options[1].click();
      });
    }
  };

Option 2 is selected by default when the page loads. What I need is to select option 1 from the dropdown. But, my code doesn't do that.

Here is the code snippet of the select option.

<select required="required" class="form-control empty ng-pristine ng-valid ng-not-empty ng-valid-required ng-touched" name="entity_id" ng-model="invoice.entity_id" ng-options="entity.company_id as entity.company_name for entity in entities" ng-required="true" ng-change="entitySelect(invoice.entity_id)">

  <option value="string:568f97841a4885e5de39900e" label="Option Global">Option Global</option>

  <option selected="selected" value="string:568f976a1a4885e5de39900d" label="Option Computer Studies">OptionComputer Studies</option>

</select>

Thanks in advance :)

Upvotes: 0

Views: 2495

Answers (3)

Kanhaiya Kumar
Kanhaiya Kumar

Reputation: 129

Got the perfect answer

var selectOption = element(by.model("invoice.entity_id")).all(by.tagName('option')); selectOption.get(1).click();

We can also get all the option value by each function

selectOption.each(function(item,index){

   //Resolve the promise
  item.getText().then(function(data){
       console.log(data+" "+index);
  });

});

Upvotes: 0

Optimworks
Optimworks

Reputation: 2547

var selectDropdownbyNum = function ( dropDown, optionNumber) {

dropDown.click().then(function(){ element.all(by.tagName('entity.company_id as entity.company_name for entity in entities')).first().click(); }); };

Upvotes: 2

TesterABC
TesterABC

Reputation: 1226

Found the perfect answer.

element.all(by.css('cssSelector of the dropdown')).each(function (eachElement, index) 
    {
       eachElement.click();// select the <select>
       browser.driver.sleep(500);// wait for the renderings to take effect
       element(by.css('cssSelector of option want to select')).click();// select the first md-option
       browser.driver.sleep(500);// wait for the renderings to take effect
   });

This works like calm :)

Upvotes: 1

Related Questions