17
<select>
    <option value=''>-- Select an Option --</option>
    @foreach ($options as $option)
        <option value='{{ $option->value }}'>{{ $option->name }}</option>
    @endforeach
</select> 

Select the first dynamic option

Michael J. Calkins
  • 32,082
  • 15
  • 62
  • 91

3 Answers3

25
$option = $I->grabTextFrom('select option:nth-child(2)');
$I->selectOption("select", $option);
$I->click("Submit");
Michael J. Calkins
  • 32,082
  • 15
  • 62
  • 91
  • 1
    Is there a way to detect the number of available options? – realtebo Jun 05 '14 at 12:37
  • Note that you can select the LAST child with: 'select option:last-child' and that you can count back from the end of the list of options with 'select option:nth-last-child(-2)' being the second-last item, etc. – Dave Aug 25 '14 at 22:48
  • 2
    Also note that for a page with multiple – Dave Aug 25 '14 at 22:55
7

I've run into the same issue quite often when starting out with Codeception. Using the recommended answer, I created a helper function in my AcceptanceTester class to make this a little easier.

public function selectFromDropdown($selector, $n)
{
    $option = $this->grabTextFrom($selector . ' option:nth-child(' . $n . ')');
    $this->selectOption($selector, $option);
}

Where $n is the position in the option list.

Then all you have to do is call it like this:

$I->selectFromDropdown('select', 1);

This has been working for me on pages that have several select's that load their option list based on the selected option of the previous select.

Collier Devlin
  • 999
  • 8
  • 8
1

sorry i do not have submit button, in my case i have to select the dropdown element and somehow need to tell the codeception to finish the selection.At the moment i can select but that select is not visible as i suppose the selection is not finished somehow.Below is my code to select the element.

$I->selectOption('//*[@class="ng-scope" and @ng-controller="dataIsland"]/*[local-  name()="select"]','partlycloudy');
shab
  • 989
  • 1
  • 15
  • 31