Guide on verifying the status of a switch toggle using Selenium and C#

I am having trouble verifying the current state of a switch ('on' or 'off') using selenium. The toggle appears in the 'on' position when the webpage loads, but it affects filter results in a table when switched off. I am unable to successfully retrieve its current state with my selenium tests.

  1. element.Selected; always returns false regardless of the toggle position
  2. element.Enabled; always returns true regardless of the toggle position
  3. string test = myToggle.GetAttribute("class"); returns the text "slider round" which is not helpful
  4. string test1 = myToggle.GetAttribute("checked"); is null
  5. string test2 = myToggle.GetAttribute("value"); is null

Below is the code snippet for the toggle switch:

<label class="switch">
<input type="checkbox" id="myToggle" checked />
<span class="slider round"></span>
</label>

The following code checks the toggle position and loads table data accordingly:

   if (Amt == currentAmt ) {
    if ($("#myToggle").prop("checked") == true) {
        loadMyProducts('NAN', $("#total").val());
    }

Here is an example of my current test setup:

    [FindsBy(How = How.XPath, Using = "//*[@id='divTestAcc']/div[1]/p[9]/label/span")]
  public IWebElement myToggle { get; set; }

    public Boolean CheckMyToogleIsOnorOFF()
    {
        string test = myToggle.GetAttribute("class");
        Console.Write("checking "+ test);

        // string test1 = myToggle.GetAttribute("checked");
        //string test2 = myToggle.GetProperty("checked");
        // .Selected always returns false
        // .Enables always returns true 

        Boolean result;
        result = myToggle.Enabled;
        bool result1 = myToggle.Selected;

        if (result == true)
        {
            Console.WriteLine("My toggle is enabled");
        }
        else
        {
            Console.WriteLine("My toggle is not enabled");
        }
        return result;
    }

Answer №1

// Have you checked the checkbox? 
var isChecked = driver.FindElement(By.XPath("//input[@type='checkbox']").Selected;

Using the .Selected attribute should help you achieve your goal. I included the driver.FindElement statement to make sure that you are targeting the correct element -- based on your description, it's unclear if the element you located and tested is the right one.

As another user mentioned, if GetAttribute("class") returns slider round, then you might be looking at the wrong element. Make sure to first locate the input element.

The XPath in your file header

//*[@id='divTestAcc']/div[1]/p[9]/label/span
will find the span element, not the input -- the input is the one marked as checked, so that's the one we need to check against.

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

Search for elements within the database by using the recursive feature of M

I am working on a search query to retrieve 'n' number of videos from a collection. The user has primary, secondary, and tertiary language preferences (Tamil(P), Hindi(S), English(T)). My goal is to first search for videos in the primary language, ...

Is there a viable alternative for dynamically adding effects now that DrawingContext's PushEffect function has been deprecated?

As I navigate through the challenges of rendering composite images with effects using a custom control, I encounter roadblocks due to deprecated functions and limitations in the rendering process. The built-in PushEffect & PopEffect functions no longer ser ...

Using XPath to retrieve the following sibling element based on text content exclusively

Is it possible to use relative XPath with Selenium to extract the text content of a following-sibling element by referencing the text content of both siblings? <table class="table"> <tbody> <tr> <td>Seeking& ...

Tips for incorporating inline images with gatsby-image

Seeking Solution In my quest to query and showcase images with a maximum width of 350px, I am hoping to have them displayed inline-block for tablets and larger screens. Ideally, each image would sit next to one another and wrap if they exceed the parent d ...

Error loading .OBJ files in Three.js on Azure, but works fine locally

I've been using three.js for webGL to load .obj files, but I'm facing an issue when trying to load .obj files on Windows Azure with Windows Server 2008. I'm using Google Chrome browser and it's showing the error below: GET 404 (Not Fo ...

Aligning a navigation bar with a hamburger menu in the center

I recently implemented a hamburger menu with some cool animations into my site for mobile devices. Now, I am facing the challenge of centering the menu on desktop screens and it's proving to be tricky. The positioning is off, and traditional methods l ...

Converting an Image to Memory Stream in JavaScript

Incorporating the jquery.qrcode library, I am able to create a QR code image that is output in the following format. <img src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAA ...

How can I extract the JSON value as a string?

I have a scenario where I define two objects. The first object, BOB, has properties "name" with a value of "bob" and "height" with a value of 185. var BOB = { "name": "bob", "height": 185 }; The second object, PROPS, references the height property from ...

What is the Java/Selenium method for turning off the "Warn before quitting" feature in Chrome?

Developing in Selenium often involves opening a new browser, and if the test fails to tear down as expected, you may find yourself having to manually quit the browser. By default, Chrome does not immediately quit when using certain keyboard shortcuts; inst ...

The blinking cursor in Google Docs is known as "kix-cursor-caret."

Although I adore Google Docs, I can't help but find the blinking cursor a bit too distracting for my liking. It seems that the latest version of Google Docs fails to comply with the operating system's setting for displaying a solid, non-blinking ...

Error message: Unable to access the state property of an undefined object

I've been attempting to integrate a react sticky header into my stepper component. However, I've encountered an issue where it doesn't render when added inside my App.js file. As a result, I've started debugging the code within App.js ...

Verify the hypertext reference of every individual element within a link and cross-reference it with the IP address of the

I've been working on creating a program to block ads, and here is the code I have so far: from selenium import webdriver url = input('Enter URL to detect ads from: ') browser = webdriver.Chrome() browser.get('http://'+url) all_ ...

What is the best way to establish and maintain lasting connections with the Firebase database while utilizing the superagent

Currently, I am following the Firebase Functions documentation on enhancing Firebase database performance. I have provided the code snippet below for your reference. const request = require('superagent'); const functions = require('fireba ...

Refresh the HTML table following each AJAX request

Each time my AJAX requests are made, new rows keep getting added to my HTML table. I need the table to be updated with fresh data on each call, without appending. This is my current code: var data = $('#data_input').val(); var tableRef = docume ...

The fixed positioned div with jQuery disappears when scrolling in Firefox but functions properly in Chrome, IE, and Safari

Click here to see a div located at the bottom of the right sidebar that is supposed to behave as follows: As you scroll down the page, the div should change its class and become fixed at the top of the screen until you reach the bottom of the parent el ...

The search functionality in an Html table is currently malfunctioning

Currently, I am working on developing a search mechanism in HTML. It seems to be functioning properly when searching for data for the first time. However, subsequent searches do not yield the expected results. Additionally, when trying to search with empty ...

"Safari (iOS) is experiencing a functionality issue where Alert() is working, but console.log() is

Just a heads up before you dive in: I've encountered an issue with Safari related to Chrome, but it seems to work fine on other browsers. So, it could be more OS-specific rather than a general problem. I recently ran into a frustrating situation whil ...

Create a full-width slider using Materialize CSS framework

When using materializecss to create a slider, I encountered an issue where the image is full width but not full height, causing scrollbars to appear. What changes can I make to ensure the slider fills out my screen without any scrollbars? Additionally, I ...

Directing to index.html using ExpressJS

JS, I am working on an express app that has various routes defined. However, I am facing an issue where if the router does not match any route, it displays index.html instead of redirecting to a specific route like '/*' as I expected. I am unsu ...

The process of retrieving request data from axios.get and storing it in the Redux store

Recently delving into Redux, I'm curious about how to retrieve request data from a GET method. Upon mounting the component, you can use axios to send a GET request to '/api/v3/products', passing in parameters like pageNumber and pageSize. ...