Selenium click() working but submit() isn't

3.3k views Asked by At

In some of my Selinium Webdriver tests, I've noticed that I'm unable to submit a form by calling submit() on any of the elements of the form, but I can call click() on the submit button just fine. I've created a simple test web page to illustrate the problem. In the example below, when I call submit(), I see the submit button. But when I call click(), the form is actually submitted and I see 'Submitted'.

<html>
  <body>
    <?php if(isset($_POST["submit"])): ?>
    Submitted
    <?php else: ?>
      <form method="post">
        <input id="submit" name="submit" type="submit" value="submit">
      </form>
    <?php endif; ?>
  </body>
</html>

I'm using this Selenium template, and here is how my test looks:

@Listeners(ScreenshotListener.class)
public class LoginTest extends SeleniumBase {
    @Test
    public void test() {
        WebDriver driver = getDriver();
        driver.get("http://localhost/test.php");
        WebElement submit = driver.findElement(By.id("submit"));
        submit.click(); // works
        // submit.submit(); // doesn't work
    }
}
1

There are 1 answers

0
B.K. On

Alright, so, I have a similar issue and I'd like to share a solution that has been serving me well thus far. On some of the web pages I have to use .Submit() and on some I have to use .Click() on the button element. The page that I have to use .Click() on, will tell me that username or password I entered is incorrect; eventhough, if I leave out the .Submit() portion and click manually, it logs in with the programatically filled in credentials. So, I had to find its button element by its id and use .Click() on it. The second website has a completely opposite behavior and does nothing when .Click() is being used on the button. Instead, .Submit() works.

So, to get around this whole mess until I figure it out (and I've bee at it for a while), here's what I've done. Most of the websites perform submission on the Enter key down event, so, that's exactly what I did.

Here's a snippet of my code:

private void Login(string url, string usernameElement, string username, 
                   string passwordElement, string password)
{
    IWebDriver driver = new FirefoxDriver();
    driver.Navigate().GoToUrl(url);
    IWebElement query = driver.FindElement(By.Id(usernameElement));
    query.SendKeys(username);
    query = driver.FindElement(By.Id(passwordElement));
    query.SendKeys(password);
    query.SendKeys(Keys.Enter);  // simulates Enter key down to submit
}

This little change saved me a whole lot of headache. I've tested it on several other websites and no issues thus far. I know it's not a complete fix of the library issue, but it's A fix.