Navigating through choices in select element using webdriverio

Sample HTML:

<select id="random_text">
    <option value="option1">asadka_TEST</option>
    <option value="option2">Peter Parker</option>
    <option value="option3">Clark Kent</option>
    <option value="option4">aldkfsd_TEST</option>
</select>

Javascript code within the class

class TestPage extends Page {

    get fullNameSelect() {return browser.element('#random_text');}

    iterateAndSelect() {
        this.fullNameSelect.value.ForEach() //pseudo code
    }
}

I am trying to make iterateAndSelect function go through all options and choose the first one that ends with "_TEST".

Currently, I have only managed to discover the selectByVisibleText action, but the issue is that I want to select an option based on a condition that the value ends with "_TEST" string, while this action requires providing the exact value.

Answer №1

To easily locate the initial option that finishes with _TEST, you can follow these steps:

const index = browser.getElements('option').findIndex(option => {
    return option.getText().endsWith('_TEST')
});

After finding the index, proceed to select the corresponding value:

browser.getElement('select').selectByIndex(index);

Answer №2

Here is a straightforward method to accomplish this task.

// retrieve all options
const choices = document.getElementById('random_text').children
// identify test options
const tests = Object.keys(choices).filter( index => choices[index].text.indexOf('_TEST') > 0)
// execute tests
tests.map(index => {
  console.log(choices[index].text)
})
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <select id="random_text">
    <option value="option1">asadka_TEST</option>
    <option value="option2">Peter Parker</option>
    <option value="option3">Clark Kent</option>
    <option value="option4">aldkfsd_TEST</option>
  </select>
</body>
</html>

Answer №3

Check out this snippet of Webdriverio code for you to test:

class SamplePage extends Page {

  get optionElements() {return browser.elements("option");}

  iterateAndFilter() {
       var filteredOptions=[];

     this.optionElements.value.forEach(function(element) {

     var text=browser.elementIdText(element.ELEMENT).value;
     if(text.endsWith('_FILTER')) {
        filteredOptions.push(text); 
     }
     console.log(filteredOptions); // all texts that end with _FILTER
    });
 }
   }
module.exports = new SamplePage();

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

Sorting an array of numbers using Javascript

Does anyone know how to properly sort an array in JavaScript? By default, the sort method doesn't work efficiently with numbers. For example: a = [1, 23, 100, 3] a.sort() The sorted values of 'a' end up being: [1, 100, 23, 3] If you hav ...

Encountering the AngularJS .Net Core routing $injector:modulerr error

I'm currently learning about .Net Core and AngularJS by following tutorials. However, I've encountered an error while attempting to implement client routing in the newest version of .Net Core with default configuration. The AngularJS error I rece ...

Is there a way to use a POST request and Mongoose in Express to add a new object?

I am struggling to figure out how to use .Router() for creating a POST request route. I have only worked with getById before. Can someone help me create a route for POST requests? ./generalRepository.js function Repository() {} Repository.prototype.getB ...

Cross-component communication in Angular

I'm currently developing a web-based application using angular version 6. Within my application, there is a component that contains another component as its child. In the parent component, there is a specific function that I would like to invoke when ...

Tips for quietly printing a PDF document in reactjs?

const pdfURL = "anotherurl.com/document.pdf"; const handleDirectPrint = (e: React.FormEvent) => { e.preventDefault(); const newWin: Window | null = window.open(pdfURL); if (newWin) { newWin.onload = () => ...

The requested style from ' was denied due to its MIME type ('text/html') not being compatible with supported stylesheet MIME types, and strict MIME checking is enforced

It's strange because my style.css file in the public folder works on one page but gives me an error on another. I'm not sure why it would work on one page and not on the other. The CSS is imported in index.html so it should work on all pages of t ...

What steps can be taken to further personalize this pre-existing jQuery sorting solution?

After coming across a solution for adding sorting capabilities to jQuery (source: jQuery sort()), I decided to tweak it to handle strings of variable lengths. Although the modified function sorts in ascending order, I found it quite effective. jQuery.fn.s ...

What is the best way for me to determine the average number of likes on a post?

I have a Post model with various fields such as author, content, views, likedBy, tags, and comments. model Post { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt id String @id @default(cuid()) author U ...

Image carousel with variable height

I'm attempting to implement a slide show of images with previous and next functionality. When the user clicks "previous," I want the images to slide to the left, and when they click "next," I want the images to slide to the right with a 0.5 second del ...

JavaScript: a single function and two calls to Document.getElementById() results in both returning "undefined"

Within my JavaScript file, I have a function that utilizes two variables: choice and courseChosen. The latter variable must be converted into an object first. In the HTML, the tags courseName and courseInfo are used for choice and courseChosen respectively ...

The Next.js API endpoint is struggling to process cross-domain POST requests

Dealing with a POST request in my NextJS application has been challenging. This particular post request is originating from a different domain. To address this issue, I included a receptor.ts file in the /pages/api directory: import { NextApiRequest, Next ...

Featuring data utilizing Ajax JSON in CodeIgniter

How can I display the data using AJAX? After making the data call to the controller, the JSON data is available but the data for "name", "address", and "telp" based on the "id_data" is not showing up. How can I display this data? Views <input id="id_d ...

Element that emulates a different element in HTML

Is it possible to have one element that can control and change multiple clone elements, mimicking every change made to the original? While JavaScript & jQuery can easily achieve this, most solutions involve separate variables or instances for each element ...

Issues with Ajax Requests

The pending requests from the Post need to be completed. I was hoping to record the JSON body of the request that comes in. Everything works fine when using Postman, but for some reason the AJAX requests are not functioning properly. Code snippet for Node ...

How can one verify the text displayed on a button using Java with WebDriver?

Snippet: String ButtonText = driver.findElement(By.xpath("//div[@id='block-success']//button")).getAttribute("text"); System.out.println(ButtonText); HTML Snippet <button class="join-btn explore-flock">Explore Flock</button> What ...

Using JavaScript, create a regular expression with variables that can be used to identify and match a specific section of

Struggling to apply a regex (with 1 variable) to compare against a HTML code page stored as text. The HTML code is separated into an array, with each element representing a snippet like the one below. Each element showcases details of fictional Houses (na ...

Optimizing jQuery Dialog for Different Window Sizes

I am currently developing a responsive website and facing a challenge. I need to implement a popup for window sizes smaller than 480px, but on desktop screens, the content should be visible without being inside the popup. I want to avoid duplicating the co ...

Sketch a line extending from one element to the next

Is there a way to create a styled line that starts from the center of one <td> element and ends at the center of another? I attempted to use the jQuery Connections plugin but it only connects the edges of the elements, not their centers. The plugin ...

Google Chrome is unable to process Jquery JSON .each() function

My website has a simple chat application that is functioning well. It uses ajax to request data in this manner: $.ajax({ url: "fetch/"+CHAT_SESSION_ID+"/"+LAST_MESSAGE_ID, dataType: "json", cache: false, success: function(data) { if (data.session_ac ...

Error encountered: Unable to access undefined properties while attempting to make an API call to AirTable using NextJS version 13.4

Currently in the process of learning how to use the App router with NextJS 13.4, I encountered an issue while attempting to make an external API call. Even though I am getting all the data correctly from Airtable, Next throws an error that disrupts my try ...