How to retrieve the chosen option from a drop-down menu in WebDriver using JavaScript without relying on the Select Class

Currently, I am in the process of utilizing Webdriver with Java. My goal is to retrieve the selected value from a combobox without relying on the Select class provided by Webdriver.

The specific markup that I am dealing with is as follows:

<select name="cmbStateName">
<option value="MH">Maharashtra</option>
<option value="HR">Harayana</option>
<option value="MP">Madhya Pradesh</option>
</select>

It's important to note that I am unable to make any modifications to the current markup. My preference for avoiding the Select class is rooted in my desire to streamline the test process using pure Java and direct interaction with the Markup. Rather than resorting to Javascript, I aim to extract the value through Core Java methods.

Answer №1

Give this a shot (writing in Java)

Try using this code snippet to retrieve the selected option text:
driver.findElement(By.name("cmbStateName")).findElement(By.xpath(".//option[@selected='selected']")).getText();

If that doesn't work, you can try getting the selected option value (e.g., MH or HR or MP) and then convert it back to display text using the following code:

driver.findElement(By.name("cmbStateName")).findElement(By.xpath(".//option[@selected='selected']")).getAttribute("value");

Answer №2

Experiment with the following C# code snippet (utilizing the Select Class available in OpenQA.Selenium.Support.UI): Select select = new Select(driver.findElement(By.xpath("//path_to_drop_down"))); select.deselectAll(); select.selectByVisibleText("Value1");

Answer №3

If you're looking to retrieve the selected value, consider implementing the following:

Here's a snippet of C# code that can help achieve this:

using OpenQA.Selenium.Support.UI;

var select = new SelectElement(Driver.FindElementByName("cmbStateName"));
return select.SelectedOption.Text;

Answer №4

Choose Your Size 75LB30KG4.46KG5/25LB15LB8/2LB

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Finding the arithmetic operator and then assigning both the operator and its index to a globally accessible variable can be accomplished through a

Hello, I am currently learning web development and as a beginner project, I am working on creating a calculator in React. My goal is to have the selected arithmetic operation ("+", "/", "-", or "X") executed when the user clicks "=". To achieve this, I s ...

Assign a value to a HubSpot hidden form field by utilizing Javascript

I have a snippet of JavaScript code placed in the head section of my website: <!-- Form ID Setter --> <script> document.querySelector('input[name=form_submission_id]').value = new Date(); </script> My objective is to automat ...

What methods can I use to adjust link distance while using the 3d-force-graph tool?

Exploring the capabilities of the 3D Force Graph from this repository has been an interesting journey for me. I am currently seeking ways to adjust the bond strength between nodes. I am specifically looking to modify either the link width or length, but ...

ng-model to interact with dynamically loaded elements

My dynamic list contains various items, such as cars, and is not of fixed length. Upon loading, the list appears as follows: itemList = [ { id: 0, name: 'bmw' }, { id: 1, name: 'audi' }, { id: 3, name: 'vw' }, ...

The computed variable in Vuex does not get updated when using the mapState function

I searched through several posts to find out what I am doing incorrectly. It seems like everything is set up correctly. MOTIVE Based on the value of COMPONENT A, I want to change hide/display content using v-show in DEPENDENT COMPONENT. ISSUE In the T ...

Exploring the Array Functionality in React

Is there a way to access the lista and add up all the values in unidades when the Producto matches both 1 and 2? [{ "id": "3WzFN", "cliente": "1", "lista": [{ "unidades": "2 ...

What is the most effective method for transferring items between arrays in JavaScript?

In my situation, I am dealing with two arrays - 'objects' and 'appliedObjects'. My goal is to find an elegant solution in Javascript and/or Angular for transferring objects from one array to another. Initially, my approach was as follo ...

What is causing the Unhandled Rejection (TypeError) error after I move the object in my Redux application and receive the message "Cannot read property 'filter' of undefined"?

I've been working on a Redux application. I've made modifications to a couple of files, and here are the changes in the two files: index.js: const store = createStore( reducer, { propReducer: { day: 1, data: [], filte ...

Setting up camera in ThreeJS

I am brand new to ThreeJS and currently trying to incorporate it into my web application. I have encountered a problem with configuring the camera. Currently, I have a perspective camera that is able to look at and move in every direction within my scene. ...

Prevent selenium browser from launching a new tab upon clicking a link

While exporting my selenium test to Python and executing it using the shell, I encountered an issue. After clicking on a link, the web-driver opened a new Firefox window but then failed to locate the input option on the page, resulting in an error. It seem ...

Click on an element that is nested within another element that can also be clicked on

I'm facing a challenge while attempting to create an accordion inside another accordion. The issue arises with the nested elements and their behavior upon clicking. Essentially, I have a parent div with the class .applicant, which expands on click by ...

Error in Typescript: A computed property name must be one of the types 'string', 'number', 'symbol', or 'any'

Here is the current code I am working with: interface sizes { [key: string]: Partial<CSSStyleDeclaration>[]; } export const useStyleBlocks = ( resolution = 'large', blocks = [{}] ): Partial<CSSStyleDeclaration>[] => { cons ...

js/jquery issue with IE: Scrolling to the bottom of a div upon page load

I have encountered an issue with my code on Internet Explorer. It works perfectly on Firefox, but when the content of the div is too high in IE, it fails to scroll to the bottom. Clicking a button to scroll to the bottom works fine, but the problem arise ...

What is the reason AJAX does not prevent page from refreshing?

Can anyone offer some guidance on using AJAX in Django? I'm attempting to create a basic form with two inputs and send the data to my Python backend without refreshing the page. Below is the AJAX code I am using: <script type="text/javascript& ...

The Selenium automation tool is experiencing longer page load times than the anticipated timeout duration

My goal is to have a maximum wait time of 15 seconds after calling the driver.get() method. The code I currently have set up looks like this: ... driver.set_page_load_timeout(15) try: driver.get(url) except TimeoutException as e: pass try: We ...

JavaScript encounters a parsing error when dealing with an async function

Ever since I developed a node.js web application, I've been utilizing MSSQL for the database. To streamline SQL functions, I crafted functions (sql.js) to handle all the necessary queries. Furthermore, I set up async function handlers (controllers.js) ...

Sending a JavaScript value to PHP after a quiz has been completed

I've created a web page where users can take quizzes. These quizzes dynamically generate questions using JavaScript each time they are accessed. Disclaimer: I'm fairly new to JavaScript. Once the user completes the quiz, they receive their fina ...

Creating a unique seal, badge, or widget in Django is a fun and rewarding project

Here are some examples of what I want to accomplish: View the gif showcasing the function Visit https://sectigo.com/trust-seal Check out another gif demonstrating the function Explore https://www.carandtruckremotes.com/ Don't miss this gif showin ...

Using CSS height 100% does not function properly when the content overflows

Here's what's going on with this code snippet: HTML <div class="one"> <div class="will-overflow"> </div> </div> CSS html, body { width: 100%; height: 100%; } .one { height: 100%; background: r ...

Utilizing dispatch sequentially within ngrx StateManagement

I have been working on a project that utilizes ngrx for state management. Although I am still fairly new to ngrx, I understand the basics such as using this.store.select to subscribe to any state changes. However, I have a question regarding the following ...