Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select checkboxes using the Selenium Java WebDriver?

How can I check the checkboxes using an id or XPath expression? Is there a method similar to select by visibletext for a dropdown?

Going through the examples given for all other related questions, I could not find a proper solution that works in a concise way that by few line or method I can check a chekbox or radio button.

A sample HTML section is below:

<tbody>     <tr>         <td>             <span class="120927">             <input id="ctl00_CM_ctl01_chkOptions_0" type="checkbox" name="ctl00$CM$ctl01$chkOptions$0"/>             <label for="ctl00_CM_ctl01_chkOptions_0">housingmoves</label>             </span>         </td>     </tr>      <tr>         <td>             <span class="120928">             <input id="ctl00_CM_ctl01_chkOptions_1" type="checkbox" name="ctl00$CM$ctl01$chkOptions$1"/>             <label for="ctl00_CM_ctl01_chkOptions_1">Seaside & Country Homes</label>             </span>         </td>     </tr> </tbody> 
like image 372
Maximus Avatar asked Feb 04 '13 08:02

Maximus


People also ask

How can you select a checkbox in Selenium WebDriver?

We can select the checkbox with Selenium. In an html document, each checkbox has an attribute type set to a value as checkbox. In order to select a checkbox, we shall first identify a checkbox with any locator and then apply the click() method to it.


1 Answers

Selecting a checkbox is similar to clicking a button.

driver.findElement(By.id("idOfTheElement")).click();

will do.

However, you can also see whether the checkbox is already checked. The following snippet checks whether the checkbox is selected or not. If it is not selected, then it selects.

if ( !driver.findElement(By.id("idOfTheElement")).isSelected() ) {      driver.findElement(By.id("idOfTheElement")).click(); } 
like image 112
Code Enthusiastic Avatar answered Sep 23 '22 20:09

Code Enthusiastic