brightpants brightpants - 25 days ago 12
Java Question

How to toggle a bootstrap switch with Selenium Java Webdriver?

For one of my tests, I need to press a bootstrap switch button, it has the following html:

<div class="bootstrap-switch-container" style="width: 93px; margin-left: -31px;">
<span class="bootstrap-switch-handle-on bootstrap-switch-primary" style="width: 31px;">ON</span>
<span class="bootstrap-switch-label" style="width: 31px;">11111&nbsp;</span>
<span class="bootstrap-switch-handle-off bootstrap-switch-default" style="width: 31px;">OFF</span>
<input name="form:taskDone" id="input_form:taskDone" type="checkbox">
</div>


I tried using

By TASK_DONE_SWITCH_LOCATOR = By.id("input_form:taskDone");
taskDoneSwitch = wait.until(ExpectedConditions.elementToBeClickable(TASK_DONE_SWITCH_LOCATOR));
taskDoneSwitch.click();


Then I receive the following exception:

Timed out after 5 seconds
Build info: version: '2.8.0', revision: '14056', time: '2011-10-06 15:53:48'
System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_131'
Driver info: driver.version: unknown
org.openqa.selenium.TimeoutException
at org.openqa.selenium.support.ui.FluentWait.timeoutException(FluentWait.java:220)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:188)
at hu.dual.webapp.customerservice.note.AbstractNoteTest.refreshEditPageTaskElements(AbstractNoteTest.java:161)
at hu.dual.webapp.customerservice.note.EditNoteTest.setTaskToDone(EditNoteTest.java:76)


The stacktrace points to this line:

taskDoneSwitch = wait.until(ExpectedConditions.elementToBeClickable(TASK_DONE_SWITCH_LOCATOR));


And then it doesn't click. How can I click it? I tried using the other fields and the ExpectedConditions.visibilityOfElementLocated as well, but I still couldn't click it.

Guy Guy
Answer Source

The : in the id attribute might cause the problem. Try to use partial id

By TASK_DONE_SWITCH_LOCATOR = By.cssSelector("[id*='input_form']");

Or

By TASK_DONE_SWITCH_LOCATOR = By.cssSelector("[id*='taskDone']");

Or both

By TASK_DONE_SWITCH_LOCATOR = By.cssSelector("[id*='input_form'][id*='taskDone']");

Edit

You can also try clicking on the parent element

By.className("bootstrap-switch-container");