How can I select checkboxes using the Selenium Java WebDriver?

Maximus picture Maximus · Feb 4, 2013 · Viewed 256.9k times · Source

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>

Answer

Code Enthusiastic picture Code Enthusiastic · Feb 4, 2013

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();
}