Press the button using Selenium WebDriver with Java

Currently, I am utilizing Selenium Webdriver for Chrome and Firefox along with Java.

After performing various actions, I stumbled upon a typical source code snippet like this:

<input type="button" value="yoyo" class="btn" onClick="SubmitForm(this, 'XYZ','_blank')" >

I am required to click the button. However, before clicking it as usual, I need to replace "XYZ" with "ABC". Is there a way to achieve this?

Could creating a new button or a form be a solution? Or maybe utilizing JavaScript in some way? Any approach would suffice.

Despite my search efforts, I have not been able to find guidance on resolving this issue. Your assistance would be greatly appreciated.

Answer №1

To dynamically change and click elements during automation at runtime, one strategy is to utilize the JavascriptExecutor in the following manner:

WebElement element = driver.findElement(By.className("btn"));

((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('onClick', arguments[1]);arguments[0].click();", element, "SubmitForm(this, 'ABC','_blank')");

Important Note:- This approach may not provide a permanent solution. The changes made will only be effective until the page is refreshed.

Hopefully this technique proves effective for you..:)

Answer №2

If you're looking to utilize the JavascriptExecutor function, check out this resource:

WebDriver driver; // Defined elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('onClick', 'SubmitForm(this, \'ABC\',\'_blank\')')");

You may have to locate the input element using XPath if it lacks an id.

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

Leverage the power of JavaScript validation combined with jQuery

Hello, I'm relatively new to the world of Javascript and jQuery. My goal is to create a suggestion box that opens when a user clicks on a specific button or div element. This box should only be visible to logged-in users. I have some knowledge on how ...

Retrieve or update the selected option value in a Select2 multiple dropdown

I'm currently using Select2 for multiselect on an input field. My goal is to identify which choice has been clicked, but when I inspect the event triggered upon clicking a choice ("choice-selected"), all I see is event.target.value which contains the ...

Navigating between routes in NEXT JS involves passing state, which can be achieved through various

Within one of my page objects, I have some data that I need to send to another page when redirecting. The code snippet below shows how I achieved this: const redirectAppointmentStep1 = (value) => { router.push({ pathname: '/Appointment/bo ...

The integration of AngularJS with a redirect feature is causing issues with sending JSON data to the database

I have encountered an issue when trying to send JSON data to a backend database. Everything works perfectly until I introduce a redirect within the newPost function using "$window.location.href = 'success.html';" Once the redirect is added, no da ...

Retrieving fresh CSS data from earlier animated elements within a Greensock timeline

In my code, I am using a TimelineLite() to perform a series of sequential tweens with .to(). What I want to achieve is accessing the output value from one of the early tweens in order to use it for constructing later tweens. Is there any way to retrieve t ...

Error encountered in React Native packager due to naming conflict between "lodash" and "yeoman-generator" libraries

Issue Description Within my current project, I am utilizing "react-native": "0.36.0" along with the following dependencies: "lodash": "^4.15.0" "yeoman-generator": "^0.24.1" Upon using versions above "^3.10.1" for "lodash" and "0.21.2" for "yeoman-gene ...

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 ...

What steps can I take to prompt Jackson to throw an error if a value for a primitive is not specified in the JSON?

Here is the code snippet: import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { System.out.println(new ObjectMapper().readValue("{} ...

Bridge for logging between Java and Rust

I am facing an issue with my Java program that uses JNI to interface with a Rust library. The problem lies in the fact that the info! calls in the Rust code do not generate any output. I suspect that this is due to the lack of initialization of the Rust lo ...

Solving templateUrl resolution of directives in Angular with RequireJS

Currently, I am using AngularJS and RequireJS in my single-page application (SPA). To organize imports efficiently, I rely on RequireJS. With RequireJS, I can utilize features like baseUrl to resolve import paths seamlessly. Now, I wish to apply the same r ...

Having trouble with jQuery variable assignments not working in Safari?

My jQuery 1.3.2 code is encountering issues with Safari 4 for reasons unknown to me. Even though all my javascript references are placed right before the closing <body> tag, I am facing difficulties with the following snippet: var status = $(' ...

Creating an alarm clock with customizable time and date formats using ReactJS with Material-UI integration

Here is the code I have written: const date = new Date(); const currentTime = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; const getDay = `${date.getDay()} ${date.getMonth()} ${date.getDate()}`; return ( <Box> < ...

Alternate the color over time using CSS

Is there a way to dynamically change the color of a div from black to white every two seconds, and then from white to black, continuously toggling as long as the div is visible? Essentially, I want the div to only be displayed when a user clicks and drag ...

Guide on converting this function into a computed property within Vue

Is it possible to concatenate a fixed directory path, which is defined in the data property, with a file name that is determined using v-for? I encountered an issue when attempting to do this using a computed property. The error message displayed was: ...

Is there a way to verify the results of a Python script within a PHP webpage?

For my school project, I am creating a PHP website where I want to implement a Python code Quiz. I envision a scenario where users can input Python code in an on-page editor/IDE and the output is checked automatically using PHP If-function to determine cor ...

Unable to forward with POST request in Node.js

I have a button on the front end that allows users to update their profile photo using the Cloudinary API. When the button is clicked, a Node.js POST request is sent with the user's data to query the database and update the profile photo URL. The func ...

Revisiting a Selenium Stale Object Pointer

(Just a heads up, I'm still in the process of learning Selenium so any tips on best practices are welcome) I'm currently working on using Selenium to input text into a field, wait for the page to load, and then extract a specific DOM element. Th ...

"Transferring a variable from the parent Layout component to its children components in Next

I am trying to figure out how to effectively pass the variable 'country' from the Layout component to its children without using state management. Basically, I want to drill it down. import { useState, useEffect } from 'react' import La ...

The web method within the aspx page is failing to execute

On page load, I am attempting to make an ajax request using the AngularJS $http service to fetch JSON data from a web method located in my User.aspx.cs page. The web method is defined as follows: [WebMethod] [ScriptMethod(ResponseFormat=ResponseForma ...

When integrating the React custom hook setValue into another component, it appears to be returning an undefined

I have created a custom useLocalStorage hook. When I directly use it in my component and try to update the value, I encounter an error stating that setValue is not a function and is actually undefined. Here's the code snippet: // Link to the original ...