46

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Maximus
  • 625
  • 1
  • 7
  • 10
  • Well what does your HTML look like? It's impossible to answer without looking at a sample, even a very brief sample, of what your page looks like. – Arran Feb 04 '13 at 09:30
  • Does this answer your question? [Click Check-box from the list of Check boxes via Selenium/Webdriver](https://stackoverflow.com/questions/11888786/click-check-box-from-the-list-of-check-boxes-via-selenium-webdriver) – Josh Correia Sep 04 '20 at 16:57

17 Answers17

68

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();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Code Enthusiastic
  • 2,827
  • 5
  • 25
  • 39
24

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();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Scott Crowe
  • 241
  • 2
  • 5
  • 4
    SendKeys also is the solution for the C# driver. Thanks. – Bob Feb 13 '14 at 21:19
  • 2
    I found I had to use the send a space key method with ChromeDriver also. Ive tested the send space key method with Chrome Drive v2.14 and IEDriver 2.44. – dmeehan Feb 10 '15 at 15:43
  • the above solution is perfect.If you want to add an extra checking if the check box is already checked or not the u can do the same like below. try{ IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal)); if (!TargetElement.Selected) { TargetElement.SendKeys(Keys.Space); } } catch (Exception e) { } – Arnab Sep 28 '15 at 18:20
  • In Python it is `.send_keys(Keys.SPACE)` instead of `.SendKeys(Keys.Space)` (3 differences). `Keys` requires `from selenium.webdriver.common.keys import Keys`. – Peter Mortensen Dec 01 '20 at 07:38
7

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();
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tedesco
  • 880
  • 6
  • 10
  • What language? The use of `.Click()` (uppercase "c") suggests it is [C#](https://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29) (like [Faiz's answer](https://stackoverflow.com/questions/14682763/how-can-i-select-checkboxes-using-the-selenium-java-webdriver/17417176#17417176)). All other bindings, including Python, use lowercase (`.click()`). – Peter Mortensen Dec 01 '20 at 11:18
5

Solution for C#

try
{
    IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));
    if (!TargetElement.Selected)
    {                    
        TargetElement.SendKeys(Keys.Space);
    }
}
catch (Exception e)
{
}
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Arnab
  • 271
  • 2
  • 7
  • 18
3

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/>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Maria
  • 31
  • 2
2

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']
Arran
  • 24,648
  • 6
  • 68
  • 78
  • 1
    Works fine for me here, with your HTML. Therefore there is something else you aren't telling us. How is it not working? Is it finding anything? – Arran Feb 04 '13 at 12:21
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
some_other_guy
  • 3,364
  • 4
  • 37
  • 55
  • Well I am able to select dropdown values using below code and want some similar option to select checkboxes and radio button. driver.findElement(By.xpath("html/body/form/div[5]/div[3]/div[1]/div[2]/table[1]/tbody/tr[1]/td/div[2]/div[2]/ul/li/select")).click(); Select option = new Select(driver.findElement(By.id("ctl00_CM_ctl00_ddlOptions"))); option.selectByVisibleText("Yes"); – Maximus Feb 04 '13 at 09:47
  • @Arran Below is the extract of my HTML. ' ' – Maximus Feb 04 '13 at 09:53
  • Sorry guys! I m new to this and do not know how differentiate code, URL and comment. – Maximus Feb 04 '13 at 09:54
  • What language? The use of `.Click()` (uppercase "c") suggests it is [C#](https://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29) (like [Faiz's answer](https://stackoverflow.com/questions/14682763/how-can-i-select-checkboxes-using-the-selenium-java-webdriver/17417176#17417176)). All other bindings, including Python, use lowercase (`.click()`). – Peter Mortensen Dec 01 '20 at 11:02
1

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();
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Faiz
  • 3,216
  • 1
  • 19
  • 25
  • Yes, this seems like a more robust solution, not making assumptions about the current state of the checkboxes. – Peter Mortensen Dec 01 '20 at 07:59
  • In Python, it is [`.is_selected()`](https://www.selenium.dev/documentation/en/webdriver/web_element/#is-element-selected) (three changes) and [`.click()`](https://www.selenium.dev/documentation/en/webdriver/browser_manipulation/#frames-and-iframes) (lowercase), respectively. – Peter Mortensen Dec 01 '20 at 11:34
1

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);
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
ra1x
  • 11
  • 1
  • In Python it is `.send_keys(Keys.SPACE)` instead of `.SendKeys(Keys.Space)` (three differences). `Keys` requires `from selenium.webdriver.common.keys import Keys`. – Peter Mortensen Dec 01 '20 at 10:47
1

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();
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dave
  • 1
0

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

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Khan
  • 139
  • 4
  • 14
0

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();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3487861
  • 340
  • 2
  • 2
0

For a partial match, do the following:

getDriver().findElement(By.cssSelector("<tag name>[id*='id pattern to look for']")).click();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RCR
  • 529
  • 9
  • 15
0

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);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dmeehan
  • 2,317
  • 2
  • 26
  • 31
0

Maybe a good starting point:

isChecked  = driver.findElement((By.id("idOftheElement"))).getAttribute("name");
if(!isChecked.contains("chkOptions$1"))
{
    driver.FindElement(By.Id("idOfTheElement")).Click();
}
Milky
  • 143
  • 4
  • 15
  • How is it different from [Scott Crowe's answer](https://stackoverflow.com/questions/14682763/how-can-i-select-checkboxes-using-the-selenium-java-webdriver/19936164#19936164) and other answers? – Peter Mortensen Dec 01 '20 at 10:42
  • What language? The use of [`.Click()`](https://www.selenium.dev/documentation/en/webdriver/browser_manipulation/#frames-and-iframes) (uppercase "c") suggests it is [C#](https://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29) (both Java and Python ruled out). All other bindings, including Python, use lowercase (`.click()`). – Peter Mortensen Dec 01 '20 at 11:38
0

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/).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
messed-up
  • 493
  • 4
  • 12
  • What language in the last part? The use of [`.Click()`](https://www.selenium.dev/documentation/en/webdriver/browser_manipulation/#switching-windows-or-tabs) (uppercase "c") suggests it is [C#](https://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29) (both Java and Python ruled out). All other bindings, including Python, use lowercase (`.click()`). – Peter Mortensen Dec 01 '20 at 11:55