brightpants brightpants - 1 year ago 136
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">

I tried using

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

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: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_131'
Driver info: driver.version: unknown
at hu.dual.webapp.customerservice.note.AbstractNoteTest.refreshEditPageTaskElements(
at hu.dual.webapp.customerservice.note.EditNoteTest.setTaskToDone(

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']");


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

Or both

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


You can also try clicking on the parent element

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download