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>
2

17 Answers 17

69

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

@ Code Enthusaiastic <code> 'driver.findElement(By.id("idOfTheElement").click();' </code> It is not working in my case. Please see my HTML code. I am using IE8 driver.
I was just trying to say how to select a check box. If the attribute id of an element is dynamic then you may need to rely on css or xpath.
Yes, this seems like a more robust solution, not making assumptions about the current state of the checkboxes.
In Python, it is .is_selected() (two changes).
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();

4 Comments

SendKeys also is the solution for the C# driver. Thanks.
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.
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) { }
In Python it is .send_keys(Keys.SPACE) instead of .SendKeys(Keys.Space) (3 differences). Keys requires from selenium.webdriver.common.keys import Keys.
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();
    }
}

1 Comment

What language? The use of .Click() (uppercase "c") suggests it is C# (like Faiz's answer). All other bindings, including Python, use lowercase (.click()).
5

Solution for C#

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

3 Comments

How is it different from previous answers?
In Python it is .send_keys(Keys.SPACE) instead of .SendKeys(Keys.Space) (three differences). Keys requires from selenium.webdriver.common.keys import Keys.
In Python, it is .is_selected() (three changes).
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/>

1 Comment

Typecast in here seems obsolete.
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']

1 Comment

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

1 Comment

In Python it is .send_keys(Keys.SPACE) instead of .SendKeys(Keys.Space) (three differences). Keys requires from selenium.webdriver.common.keys import Keys.
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.

4 Comments

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");
@Arran Below is the extract of my HTML. '<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>'
Sorry guys! I m new to this and do not know how differentiate code, URL and comment.
What language? The use of .Click() (uppercase "c") suggests it is C# (like Faiz's answer). All other bindings, including Python, use lowercase (.click()).
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();
    }
}

3 Comments

Yes, this seems like a more robust solution, not making assumptions about the current state of the checkboxes.
In Python, it is .is_selected() (two changes).
What language is this? Java? (The question specified Java, but at least 3 answers have used C#.)
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();
    }
}

2 Comments

Yes, this seems like a more robust solution, not making assumptions about the current state of the checkboxes.
In Python, it is .is_selected() (three changes) and .click() (lowercase), respectively.
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();
}

2 Comments

How is it different from Scott Crowe's answer and other answers?
What language? The use of .Click() (uppercase "c") suggests it is C# (both Java and Python ruled out). All other bindings, including Python, use lowercase (.click()).
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.

1 Comment

In Python, it is .is_selected() (two changes).
0

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

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

Comments

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

Comments

0

For a partial match, do the following:

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

Comments

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

2 Comments

In Python it is .send_keys(Keys.SPACE) instead of .SendKeys(Keys.Space) (three differences). Keys requires from selenium.webdriver.common.keys import Keys.
In Python it is .click() (lowercase).
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/).

1 Comment

What language in the last part? The use of .Click() (uppercase "c") suggests it is C# (both Java and Python ruled out). All other bindings, including Python, use lowercase (.click()).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.