0

Checking and unchecking of a checkbox using Selenium WebDriver.

I am using the page object pattern, so my code appears this way.

SelectCheckBox("Check");  OR  SelectCheckBox("Uncheck");

[FindsBy(How = How.Id, Using = "payment_sameasdeliveryaddress")]
public IWebElement checkbox_Address = null;

public void SetCheckBox(string value)
{
    //Console.Write("checkbox state: " + checkbox_Address.Selected);
    if (value.ToLower().Equals("uncheck") && checkbox_Address.Selected)
    {
        checkbox_Address.Click();
    }
    else if (value.ToLower().Equals("check") && !checkbox_Address.Selected)
    {
        checkbox_Address.Click();
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arpan Buch
  • 1,380
  • 5
  • 19
  • 41

4 Answers4

1

It has been years since I wrote any .NET, so the below may not even compile! But hopefully you get the idea.

// The individual elements should be declared private
private IWebElement payment_sameasdeliveryaddress;
// If you name it same as the source element
// ID, PageFactory will find it for you

// flag = true, means you want it checked
public void SelectCheckBox(Boolean check)
{
    if (!check && payment_sameasdeliveryaddress.Selected) {
        payment_sameasdeliveryaddress.Click();
    }
    else if (check && !payment_sameasdeliveryaddress.Selected) {
        payment_sameasdeliveryaddress.Click();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SiKing
  • 10,003
  • 10
  • 39
  • 90
1

This would also work:

// flag = true, means you want it checked
public void SelectCheckBox(Boolean check)
{
    if (check ^ payment_sameasdeliveryaddress.Selected) {
        payment_sameasdeliveryaddress.Click();
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kevin Burton
  • 2,032
  • 4
  • 26
  • 43
1

The simplest way of checking a checkbox is checked or not by using the isSelected() method with an element. For example:

if(getCheckBox().isSelected()){
    getCheckBox.click();
}

public WebElement getCheckBox(){
    return driver.findElement(termsCheck);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jamil
  • 11
  • 1
0

Sharing the snippet that's just implemented in the current project using Selenium WebDriver 3.9.1 and TestNG 6.14.

// Returns boolean value based on whether check-box is selected or not
Boolean chkBx1Sel = driver.findElement(By.xpath(elementXpath)).isSelected();

Case 1: Check a check-box

if(dataValofChkBx != null && dataValofChkBx.equalsIgnoreCase("Y"))
{
   if(chkBx1Sel.toString() == "false")  //i.e., checkbox is not already checked
   {
      driver.findElement(By.xpath(POP2GUIConstants.ggsnFwlfUpdChkBx)).click();
    }
}

Case 2: Uncheck a check-box

if(dataValofChkBx != null && dataValofChkBx.equalsIgnoreCase("N"))
{
   if(chkBx1Sel.toString() == "true")  // I.e., checkbox is already checked
   {
     driver.findElement(By.xpath(POP2GUIConstants.ggsnFwlfUpdChkBx)).click();
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ShrutiM
  • 1
  • 2