Tips for choosing an option in a form using Selenium with JavaScript

I am currently in the process of automating some tests for a specific form, and I have successfully automated all steps except for selecting an option from a dropdown menu using JavaScript.

Here is my code:

    const {Builder, By, Key} = require("selenium-webdriver");

      async function automateSelection() {

        // Launch the browser
        let driver = await new Builder().forBrowser("chrome").build();
        // Navigate to our application
        await driver.get("https://dev.septemcompliance.com/designer/design.aspx? 
        c=0asrnQyA%2bharoubJy0g6zqq%2fVssaPaDM6m0yv7hD0hTwY8bXo%2bNQLRsUzDolSOAT")
        // Fill in login details
        await driver.findElement(By.id("TxtLogin")).sendKeys("joao")
        await driver.findElement(By.id("TxtPassword")).sendKeys("010445jv")
        await driver.findElement(By.id("BtnLogin")).click()
        await driver.findElement(By.id("HlOpenSimulation")).click()
        await driver.findElement(By.id("HlStartSimulation")).click()
        await driver.findElement(By.name("inp12082")).click();
        await driver.findElement(By.xpath("//* 
        [@id=td1secretaria_municipal]/select/option[1]")).click();

      }
      automateSelection()

Upon inspecting the select element that I need to automate, this is the code snippet extracted from the website:

<select label="Secretaria municipal" name="inp12082" xname="inpsecretaria_municipal" 
        xtype="SELECT" required="S" style="width:350px" 
onchange="controlValueChange(this);salvarSecretaria($(this));atualizarSecretariasExecutivas();" 
             data-c="DSe28HiL3BwUi7ITIAiFKoPYC2jIQnf-1ElLrN9eVsFFzP- 
             O91XnU@emdmWvie5Aqx3Arj6ROWUKqAGZrCQsDjwO5geI9nuTiU9JlTlMz2hbH5D3M1D-E5loLjoTSRcU">
  <option value="">Selecione</option><option value="1">SECRETARIA 1</option>
</select>

Answer №1

If my understanding is correct, all you need is a simple CSS selector and then utilize the click method.

<select>
  <option value="1" selected="selected">one</option>
  <option value="2">two</option>
</select>
const item = await driver.findElement(By.css('select option[value="2"]'));
await item.click();

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

The issue arises with proptypes validation while implementing material-ui components

Just embarked on a new ReactJS project and ran into a plethora of errors when I integrated material-ui. One of the errors looked like this: bundle.js:12441 Warning: Failed Context Types: Calling PropTypes validators directly is not supported by the prop ...

Include a function call within a ternary operator in JSX code

I am looking to call a function within a ternary operator condition. Here is what my code looks like: {snapshot.Bid[0].Price !== 'undefined' ? `(${initialOrderInfo.snapshot.Bid[0].Price}` {renderCurrencySymb ...

Pandas Read HTML doesn't have the ability to extract information from interactive images

Currently, I am in the process of extracting data from the website located at: The table on this site is displayed as follows: https://i.sstatic.net/rAIxe.png Specifically, my goal is to scrape this table while also capturing the clickable links found un ...

Is there a way in React to specify which properties to pass (and when to pass them) to child components based on the properties of the parent component?

In this hypothetical scenario, there are 4 components already in place: MainComponent1, MainComponent2, IntermediateComponent, and ChildComponent. Both MainComponent1 and MainComponent2 can utilize IntermediateComponent as their child component, while Chil ...

Toggle classes on button click

<div class='fixed_button homes hidden'> <a class='btn btn-primary homes'>Continue &rarr;</a> </div> Using jQuery Library $(".homes").on('click', function(){ $("choose_style").addClass(&apo ...

Differences in weekend start and end days vary across cultures

Looking for a solution to determine the weekend days per culture code in Typescript/Javascript? While most countries have weekends on Sat-Sun, there are exceptions like Mexico (only Sunday) and some middle-eastern countries (Fri-Sat). It would be helpful ...

What is causing this form to submit?

I need help with sending emails via AJAX. My problem is that the form keeps submitting and refreshing, even though I haven't used GET to send anything in the URL. HTML: <form onsubmit="ajaxEmail(); return false;" > <input type=" ...

Employing Visual Composer within WordPress has resulted in the raw JavaScript not being properly applied to my raw HTML code

Sharing some code that functions properly in my browser and I want to implement on my WordPress page: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8> <!-- Getting jQuery --> <script src="http://ajax.goog ...

Avoiding the selection of HTML canvas objects

I am currently working on customizing my homepage with an interactive animation. However, I am facing some challenges in integrating it seamlessly into the page. You can view the progress at . My main issue is preventing the canvas object from being select ...

- Determine if a div element is already using the Tooltipster plugin

I have been using the Tooltipster plugin from . Is there a way to check if a HTML element already has Tooltipster initialized? I ask because sometimes I need to update the text of the tooltip. To do this, I have to destroy the Tooltipster, change the tit ...

Retrieve a text value from a piece of code

I need help finding the string: "Plan B Warranty & Breakdown Recovery" in the code block below. I'm struggling to locate it using xpath and get text functions. Any advice would be greatly appreciated. <!DOCTYPE html> <html class="ng-scop ...

What causes useEffect to run twice in React and what is the best way to manage it effectively?

I'm currently facing an issue with my React 18 project where the useEffect hook is being called twice on mount. I have a counter set up along with a console.log() inside the useEffect to track changes in state. Here's a link to my project on Code ...

Retrieve the body's coordinates when dragging an element using the jQuery UI library

How can I obtain the coordinates of a dragged div upon drag and drop action, including left, right, and top positions? Additionally, how do I then use Ajax to post these coordinates? An example link can be found at jsfiddle.net/qPw92 <html> &l ...

Trouble with Bootstrap 3's nav-justified feature not displaying correctly upon window expansion

Looking at this Bootstrap example page, I noticed a small issue with the nav-justified navigation. When the window is minimized, it transitions correctly to a mobile version. However, when the window is maximized again, the buttons remain in the mobile for ...

Using `preventDefault()` will also block any text input from being entered

Note: I am looking for a way to clear the text box using the enter key after typing some text. My apologies for any confusion caused. Update 2: The missing event parameter was causing all the issues. I feel like a failure as a programmer. I am trying to ...

A guide on integrating a stacked bar chart from ApexCharts into a modal or v-dialog component

I'm facing a minor issue with vue-apexcharts while attempting to showcase some data in a stacked bar chart. Here is the simple component I have created: <template> <div v-if="this.loaded"> <apexchart w ...

Unable to apply ready function in jquery .load

When the document is ready, the following code is executed: jQuery(document).ready(function(){ jQuery('#button').click(function() { jQuery('#contact_form').load("/Users/mge/Downloads/jquery-ajax-1/readme.txt"); ...

Instructions on removing rows by using buttons within a JavaScript-generated table

This snippet displays JS code to create a quiz index table and HTML code to display the index. function load(){ var data = [ { "id": "qc1111", "quizName": "Quiz1", "course": "111", "dueDate": "1/ ...

working with JSON array information

I have a JSON array retrieved from a database that I need to manipulate. Currently, it consists of 8 separate elements and I would like to condense it down to just 2 elements while nesting the rest. The current structure of my JSON looks like this: { "i ...

Having trouble decoding audio data in JavaScript Web Audio?

I'm attempting to utilize the Web Audio API in JavaScript to upload a sound into a buffer and play it. However, I am encountering an issue where it does not work and an error message is displayed: Uncaught TypeError: Failed to set the 'buffer&ap ...