Clicking label element that unfortunately contains a link

1.7k views Asked by At

I'm running into an issue where I'm attempting to click on a checkbox. The app is written in AngularJS.

The checkbox can not be clicked, as technically the element is not visible. Using 'visible: false' does not help to get this box checked. I have also tried to use element.set(true)

The checkbox is within a label element that happens to also contain hyperlinks. Since Capybara/Selenium clicks on the middle of an element by default, I end up opening the hyperlink instead of marking the checkbox. Clicking within anywhere in the label (outside of the hyperlinks) checks the box successfully.

How can I achieve this?

3

There are 3 answers

0
Phil On BEST ANSWER

Took me a little while but I figured out that I can avoid the Capybara API and use WebDriver's ActionBuilder.

def agree
  source = find('label.terms-label').native
  actionbuilder = page.driver.browser.action
  actionbuilder.move_to(source, 0, 0).click.perform
end

By default, the Capybara API (as well as other native Selenium methods) will click in the center of the element. This will avoid that and will find the element and click it at (0, 0) coordinates.

0
Kudin On

I would recommend using JavascriptExecutor to click element. In case element is technically not visible Webdriver will not allow you to click it using API, as it tries to simulate real user actions. Nevertheless you have the option to execute JS directly, which doesn't really care.

This answer will help you with the code part: https://stackoverflow.com/a/19934852/2998104

You would need to change ending slightly to:

JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.xpath("exact_locator_of_checkbox"));
js.executeScript("arguments[0].click()",element);

Of course no need to use only xpath, but anything that help you point to the checkbox directly.

0
Nathan Wallace On

As of Capybara 3.0.0, you can specify an offset when you call click on an element. So if you want to click the top-left corner of the element box, you'd say:

find('label.terms-label').click(x: 0, y: 0)

(Note, you must specify :x and :y if you specify either)