1

I want mark some checkboxes as checked using Selenium and Java, but in the .css style sheet their "width" and "height" is set to "100", yet in the browser they appear as normal checkboxes. Because of this selenium finds them and succesfully executes .click() function, but the checkbox does not get selected. Is there a way to simply set the checkbox as selected without using .click() ?

2 Answers2

1

Difficult to say without a reproducible sample, but you may try clicking via javascript:

WebElement checkbox = driver.findElement(By.ID("mycheckbox"));

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", checkbox);

See here the differences:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Isn't this similar to the click() with an additional overhead of invoking the JS executor? – codeMan Feb 01 '16 at 14:17
  • 1
    @codeMan nope, these are quite different: http://stackoverflow.com/questions/34562061/webdriver-click-vs-javascript-click. – alecxe Feb 01 '16 at 14:17
  • I did not know this! The author also says this should be used "almost never". – codeMan Feb 01 '16 at 14:21
  • 1
    @codeMan well, that depends on what are you trying to do. If this is for scraping purposes, or a workaround to tackle browser-specific issues, it is pretty much okay. It should be avoided when UI testing applications in general, I agree. – alecxe Feb 01 '16 at 14:22
1

Im afraid there is no select() method on a check box, but you could write something like this and reuse it.. which will abstract the operation of select

if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
    driver.findElement(By.id("idOfTheElement")).click();
}
codeMan
  • 5,730
  • 3
  • 27
  • 51