Maximus
Maximus

Reputation: 625

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>

Upvotes: 46

Views: 271834

Answers (17)

Code Enthusiastic
Code Enthusiastic

Reputation: 2847

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

Upvotes: 68

Faiz
Faiz

Reputation: 3256

A solution using WebDriver and C# is below. The key idea is to get the ID of the checkbox from the labels' 'for' attribute, and use that to identify the checkbox.

The code will also set the checkbox state only if it needs to be changed.

public void SetCheckboxStatus(string value, bool toCheck)
{
    // Get the label containing the checkbox state
    IWebElement labelElement = this.Driver.FindElement(By.XPath(string.Format("//label[.='{0}']",value)));
    string checkboxId = labelElement.GetAttribute("for");

    IWebElement checkbox = this.Driver.FindElement(By.Id(checkboxId));

    if (toCheck != checkbox.Selected)
    {
        checkbox.Click();
    }
}

Upvotes: 1

Puneet Ghildiyal
Puneet Ghildiyal

Reputation: 21

The below code will first get all the checkboxes present on the page, and then deselect all the checked boxes.

List<WebElement> allCheckbox = driver.findElements(By
    .xpath("//input[@type='checkbox']"));

for (WebElement ele : allCheckbox) {
    if (ele.isSelected()) {
        ele.click();
    }
}

Upvotes: 1

messed-up
messed-up

Reputation: 533

I tried with various approaches, but nothing worked. I kept getting "Cannot click element" or ElementNotVisibleException.

I was able to find the input, but I couldn't check it. Now, I'm clicking on the div that contains the checkbox and it works with following HTML (CSS based on Bootstrap).

 @foreach (var item in Model)
 {
     <tr>
         <td>
             <div id="@item.Id" class="checkbox">
                 <label><input type="checkbox" class="selectone" value="@item.Id"></label>
             </div>
         </td>
         <td val="@item.Id">
             @item.Detail
         </td>
         <td>
             <div>@item.Desc
             </div>
         </td>
         <td>
             @Html.ActionLink("Edit", "Create", new { EditId = item.Id })
         </td>
     </tr>
 }

This is the code for WebDriver:

var table = driver.FindElement(By.TagName("table"));
var tds = table.FindElements(By.TagName("td"));
var itemTds = tds.Where(t => t.Text == itemtocheck);
foreach (var td in itemTds)
{
    var CheckBoxTd = tds[tds.IndexOf(td) - 1];
    var val = td.GetAttribute("val");
    CheckBoxTd.FindElement(By.Id(val)).Click();
}

In this approach, I give the item id as id for the div and also add an attribute for td with that id. Once I find the td of the item that needs to be checked, I can find the div before that td and click it. We can also use the XPath query that supports before (here is the example http://learn-automation.com/how-to-write-dynamic-xpath-in-selenium/).

Upvotes: 0

dmeehan
dmeehan

Reputation: 2357

Here is the C# version of Scott Crowe's answer. I found that both IEDriver and ChromeDriver responded to sending a Key.Space instead of clicking on the checkbox.

if (((RemoteWebDriver)driver).Capabilities.BrowserName == "firefox")
{
    // Firefox
    driver.FindElement(By.Id("idOfTheElement")).Click();
}
else
{
    // Chrome and Internet Explorer
    driver.FindElement(By.Id("idOfTheElement")).SendKeys(Keys.Space);
}

Upvotes: 0

RCR
RCR

Reputation: 539

For a partial match, do the following:

getDriver().findElement(By.cssSelector("<tag name>[id*='id pattern to look for']")).click();

Upvotes: 0

user3487861
user3487861

Reputation: 350

Step 1:

The object locator supposed to be used here is XPath. So derive the XPath for those two checkboxes.

String housingmoves="//label[contains(text(),'housingmoves')]/preceding-sibling::input";
String season_country_homes="//label[contains(text(),'Seaside & Country Homes')]/preceding-sibling::input";

Step 2:

Perform a click on the checkboxes

driver.findElement(By.xpath(housingmoves)).click();
driver.findElement(By.xpath(season_country_homes)).click();

Upvotes: 0

Scott Crowe
Scott Crowe

Reputation: 241

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

Upvotes: 24

Khan
Khan

Reputation: 139

To select a checkbox, use the "WebElement" class.

To operate on a drop-down list, use the "Select" class.

Upvotes: 0

Tedesco
Tedesco

Reputation: 880

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

Upvotes: 7

Dave
Dave

Reputation: 1

Running this approach will in fact toggle the checkbox; .isSelected() in Java/Selenium 2 apparently always returns false (at least with the Java, Selenium, and Firefox versions I tested it with).

The selection of the proper checkbox isn't where the problem lies -- rather, it is in distinguishing correctly the initial state to needlessly avoid reclicking an already-checked box.

Upvotes: 0

Maria
Maria

Reputation: 31

You can use the following code:

List<WebElement> checkbox = driver.findElements(By.name("vehicle"));
((WebElement) checkbox.get(0)).click();

My HTML code was as follows:

<.input type="checkbox" name="vehicle" value="Bike">I have a bike<br/>
<.input type="checkbox" name="vehicle" value="Car">I have a car<br/>

Upvotes: 3

some_other_guy
some_other_guy

Reputation: 3394

This should help -

IWebElement elementToClick = driver.findElement(By.xpath(""//input[contains(@id, 'lstCategory_0')]"));
elementToClick.Click();

You can also pass an id.

If you want something like visible text you can "find element" by name if they have names.

Upvotes: 1

Arnab
Arnab

Reputation: 271

Solution for C#

try
{
    IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));
    if (!TargetElement.Selected)
    {                    
        TargetElement.SendKeys(Keys.Space);
    }
}
catch (Exception e)
{
}

Upvotes: 5

ra1x
ra1x

Reputation: 11

I found that sometimes JavaScript doesn't allow me to click the checkbox because was working with the element by onchange event.

And that sentence helps me to allow the problem:

driver.findElement(By.xpath(".//*[@id='theID']")).sendKeys(Keys.SPACE);

Upvotes: 1

Milky
Milky

Reputation: 153

Maybe a good starting point:

isChecked  = driver.findElement((By.id("idOftheElement"))).getAttribute("name");
if(!isChecked.contains("chkOptions$1"))
{
    driver.FindElement(By.Id("idOfTheElement")).Click();
}

Upvotes: 0

Arran
Arran

Reputation: 25056

To get the checkbox for 'Seaside & Country Homes', use this XPath:

//label[text()='Seaside & Country Homes']/preceding-sibling::input[@type='checkbox']

To get the checkbox for 'housingmoves', use this XPath:

//label[text()='housingmoves']/preceding-sibling::input[@type='checkbox']

The principle here is to get the label with the text you want, then get the checkbox that is before the label, since that seems to be how your HTML is laid out.

To get all checkboxes, you would start a little higher up and then work down, so that is to say get the table, and then get any checkbox within a span:

//table/descendant::span/input[@type='checkbox']

Upvotes: 2

Related Questions