0
0
Selenium Javatesting~5 mins

Submitting forms in Selenium Java

Choose your learning style9 modes available
Introduction

Submitting forms lets you send data on a webpage to the server. It helps test if the form works correctly.

When testing a login page to check if user credentials are accepted.
When verifying a registration form submits user details properly.
When checking if a search form returns results after submission.
When testing contact forms to ensure messages are sent.
When automating checkout processes in online shopping sites.
Syntax
Selenium Java
WebElement formElement = driver.findElement(By.id("formId"));
formElement.submit();

The submit() method sends the form data to the server.

You can call submit() on any element inside the form, like an input or the form itself.

Examples
Submit the form with id 'loginForm' directly.
Selenium Java
driver.findElement(By.id("loginForm")).submit();
Submit the form by calling submit on an input element inside the form.
Selenium Java
driver.findElement(By.name("username")).submit();
Find a form by CSS class and submit it.
Selenium Java
WebElement form = driver.findElement(By.cssSelector("form.contact"));
form.submit();
Sample Program

This test opens a login page, fills username and password, submits the form, and prints the URL after submission.

Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class SubmitFormTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com/login");
            WebElement username = driver.findElement(By.id("username"));
            WebElement password = driver.findElement(By.id("password"));
            username.sendKeys("testuser");
            password.sendKeys("testpass");
            WebElement form = driver.findElement(By.id("loginForm"));
            form.submit();
            String currentUrl = driver.getCurrentUrl();
            System.out.println("Current URL after submit: " + currentUrl);
        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

Make sure the form element or an element inside the form is located before calling submit().

If the form has JavaScript handling submission, submit() triggers the normal submit event.

Always close the browser with driver.quit() to free resources.

Summary

Use submit() to send form data in Selenium tests.

You can call submit() on the form or any child element inside it.

Submitting forms helps verify user input is processed correctly on web pages.