Rahil Kumar
Rahil Kumar

Reputation: 428

How can I use Cypress to select an <option> in a specific HTML <select> field?

I Want to select Options from the below HTML Code. timeentry_lov1 is Select Name which is the 2nd element in Page with the same Name. Also I checked that there is no Frame present in Page. But Is there any Frame Concept like selenium in Cypress? If not then how do I work with Select attribute?

HTML:

enter image description here]1

The below Select Statement which I have tried:

cy.get('timeentry_lov1',{timeout : 60000}).eq(1).select('NB-860').debug();
cy.get('timeentry_lov1').eq(1).select('NB-860-Test Automation');
cy.select('timeentry_lov1',{timeout : 7000}).eq(1).should('have.value','NB-860');
cy.find('timeentry_lov1').get('select').select('NB-860');

Upvotes: 1

Views: 1394

Answers (1)

Zach Bloomquist
Zach Bloomquist

Reputation: 5881

To find all <select> elements with a name equal to "timeentry_lov1" in the page, use a CSS selector that filters on the name attribute, like this:

cy.get('select[name="timeentry_lov1"]')

To select only the second <select> tag, you can use :nth-of-type(2) to select only the second element that is found:

cy.get('select[name="timeentry_lov1"]:nth-of-type(2)')

Now, to actually select the element, just use cy.select() with the value of the <option> you want to select:

cy.get('select[name="timeentry_lov1"]:nth-of-type(2)')
.select('NB-860')

That should accomplish what you're trying to do.


Tip: you can use Cypress's Selector Playground to help you find good CSS selectors to use in your tests. Check out the docs for a video on how it works.

Upvotes: 3

Related Questions