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>

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

It appears that the Internet Explorer driver does not interact with everything in the same way the other drivers do and checkboxes is one of those cases.

The trick with checkboxes is to send the Space key instead of using a click (only needed on Internet Explorer), like so in C#:

if (driver.Capabilities.BrowserName.Equals(“internet explorer"))
    driver.findElement(By.id("idOfTheElement").SendKeys(Keys.Space);
else
    driver.findElement(By.id("idOfTheElement").Click();

If you want to click on all checkboxes at once, a method like this will do:

private void ClickAllCheckboxes()
{
    foreach (IWebElement e in driver.FindElements(By.xpath("//input[@type='checkbox']")))
    {
        if(!e.Selected)
            e.Click();
    }
}